0%
CSS 置中方式
- demo heml
1 2 3 4 5
| <div class="container"> <div class="content"> content </div> </div>
|
![](https://i.imgur.com/FjGAHa9.png)
水平置中
block + margin
1 2 3 4 5 6 7 8 9 10 11 12
| .container { border: 1px solid black; }
.content { display: block; // default width: 200px; height: 200px; background-color: lightblue; margin: 0 auto; }
|
![](https://i.imgur.com/pGXrpFg.png)
inline-block + text-align
1 2 3 4 5 6 7 8 9 10 11 12
| .container { border: 1px solid black; text-align: center; }
.content { display: inline-block; width: 200px; height: 200px; background-color: lightblue; margin: 0 auto; }
|
![](https://i.imgur.com/yjPfCPS.png)
垂直置中
height = line-height
1 2 3 4 5
| .content { height: 200px; background-color: lightblue; line-height: 200px; }
|
![](https://i.imgur.com/G6efvNo.png)
relative and absolute position + margin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| .container { border: 1px solid black; height: 400px;
position: relative; }
.content { position: absolute;
width: 200px; height: 200px; background-color: lightblue;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto; }
|
![](https://i.imgur.com/IxUu1os.png)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| .container { border: 1px solid black; height: 400px;
position: relative; }
.content { position: absolute;
width: 200px; height: 200px; background-color: lightblue;
top: 50%; left: 50%;
transform: translate(-50%, -50%); }
|
![](https://i.imgur.com/tvCkBOW.png)
flex
1 2 3 4 5 6 7 8 9
| .container { border: 1px solid black; height: 400px;
display: flex; justify-content: center; align-items:center; }
|
![](https://i.imgur.com/u7fUR2Q.png)
table
1 2 3 4 5 6 7
| <table> <tr> <td class="content"> content </td> </tr> </table>
|
1 2 3 4
| .content { text-align: center; vertical-align: middle; }
|
![](https://i.imgur.com/RaS8e3p.png)