1.1行內元素水平居中:text-alignhtml
1 <head> 2 <style> 3 #box { 4 width: 200px; 5 height: 200px; 6 border: 1px solid red; 7 /* 行內元素水平 */ 8 text-align: center; 9 } 10 </style> 11 </head> 12 <body> 13 <div id="box"> 14 <span>我要居中</span> 15 </div> 16 </body> 17 </html>
1.2塊級元素水平居中:marginide
<head> <style> #box1 { width: 300px; height: 300px; background-color: red; } #box2 { width: 100px; height: 100px; background-color: green; margin: 0 auto; } </style> </head> <body> <div id="box1"> <div id="box2">我是塊元素,我想水平居中</div> </div> </body> </html>
2.1行內元素垂直居中(僅限於單行文本):line-heightflex
<head> <style> #box1 { width: 300px; height: 300px; background-color: red; line-height: 300px; } </style> </head> <body> <div id="box1"> 我是子元素 </div> </body> </html>
3.1行內元素:text-align + line-heightspa
1 <head> 2 <style> 3 #box1 { 4 width: 300px; 5 height: 300px; 6 background-color: red; 7 line-height: 300px; 8 text-align: center; 9 } 10 </style> 11 </head> 12 <body> 13 <div id="box1"> 14 我是子元素 15 </div> 16 </body> 17 </html>
效果:3d
3.2.定位+transform
code
優勢:元素寬高改變的時候不要再計算orm
缺點:有兼容性問題htm
1 <head> 2 <style> 3 #parent { 4 width: 300px; 5 height: 300px; 6 background-color: red; 7 position: relative; 8 } 9 .child { 10 width: 100px; 11 height: 100px; 12 background-color: green; 13 position: absolute; 14 left: 50%; 15 top:50%; 16 transform: translate(-50%,-50%); 17 } 18 </style> 19 </head> 20 <body> 21 <div id="parent"> 22 <div class="child">子元素</div> 23 </div> 24 </body> 25 </html>
效果:blog
3.3定位+marginit
缺點:不夠動態,寬高改變須要程序計算
1 <head> 2 <style> 3 #parent { 4 width: 300px; 5 height: 300px; 6 background-color: red; 7 position: relative; 8 } 9 .child { 10 width: 100px; 11 height: 100px; 12 background-color: green; 13 position: absolute; 14 left: 50%; 15 top:50%; 16 margin-left: -50px; 17 margin-top: -50px; 18 } 19 </style> 20 </head> 21 <body> 22 <div id="parent"> 23 <div class="child">子元素</div> 24 </div> 25 </body> 26 </html>
效果圖:
3.4彈性盒模型:
1 <head> 2 <style> 3 #parent { 4 width: 300px; 5 height: 300px; 6 background-color: red; 7 display: flex; /* 父元素設置flex*/ 8 align-items: center; /* 垂直居中 */ 9 justify-content: center; /* 水平居中 */ 10 } 11 .child { 12 width: 100px; 13 height: 100px; 14 background-color: green; 15 } 16 </style> 17 </head> 18 <body> 19 <div id="parent"> 20 <div class="child">子元素</div> 21 </div> 22 </body> 23 </html>
效果:
3.5.display:table實現(不經常使用):
1 <head> 2 <style> 3 #parent { 4 width: 300px; 5 height: 300px; 6 background-color: red; 7 display: table; 8 text-align: center; 9 } 10 .child { 11 display: table-cell; 12 background-color: green; 13 vertical-align: middle; 14 } 15 </style> 16 </head> 17 <body> 18 <div id="parent"> 19 <div class="child">子元素</div> 20 </div> 21 </body> 22 </html>
效果: