元素⽔平垂直居中的⽅法
实现元素⽔平垂直居中的⽅式:
•
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <style> .father{ width:500px; 1 2 3 4 height:300px; 5 border:1px solid #0a3b98; 6 position: relative; 7 } 8 .son{ 9 width:100px; 10 height:40px; 11 background: #f0a238; 12 position: absolute; 13 top:0; 14 left:0; 15 right:0; 16 bottom:0; 17 margin:auto; 18 } 19 </style> 20 <div class="father"> 21 <div class="son"></div> 22 </div>
|
利⽤定位+margin:auto
⽗级设置为相对定位,⼦级绝对定位 ,并且四个定位属性top,left,right,bottom的值都设置了0,那么这时候如果⼦级没有设
置宽⾼,则会被拉开到和⽗级⼀样宽⾼
这⾥⼦元素设置了宽⾼,所以宽⾼会按照我们的设置来显⽰,但是实际上⼦级的虚拟占位已经撑满了
整个⽗级,这时候再给它⼀个 margin:auto 它就可以上下左右都居中了
•
table布局
设置⽗元素为 display:table-cell ,⼦元素设置 display: inline-block 。利⽤
vertical 和 text-align 可以让所有的⾏内块级元素⽔平垂直居中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| 1 <style> 2 .father { 3 display: table-cell; 4 width: 200px; 5 height: 200px; 6 background: skyblue; 7 vertical-align: middle; 8 text-align: center; 9 } 10 .son { 11 display: inline-block; 12 width: 100px; 13 height: 100px; 14 background: red; 15 } </style> <div class="father"> <div class="son"></div> </div>
|
•
flex布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <style> .father { display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; background: skyblue; } .son { width: 100px; height: 100px; background: red; } </style> <div class="father"> <div class="son"></div> </div>
|
这⾥可以简单看看 flex 布局的关键属性作⽤:
display: flex时,表⽰该容器内部的元素将按照flex进⾏布局
align-items: center表⽰这些元素将相对于本容器⽔平居中
justify-content: center也是同样的道理垂直居中