块元素的居中
块元素特点:
1 2 3 4 5 6 7 8 9 10
| .outer { width: 500px; height: 500px; border: 1px solid black; } .inner { width: 100px; height: 100px; background-color: purple; }
|
1 2 3 4 5
| <div class="outer"> <div class="inner">
</div> </div>
|
两个盒子, 如何让inner在outer中, 垂直水平居中?
方式一
通过flex布局, 首选, 无需计算, 简单
支持行内元素, 行内块元素的居中, 因为flex布局后, 其子元素默认变为块元素
方式二
较简洁, 但是需要简单的计算, 且inner高度改变时, 会影响垂直居中
不支持行内元素的居中(当inner的元素从div变成span时)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .outer { width: 500px; height: 500px; border: 1px solid black; } .inner { width: 100px; height: 100px; background-color: purple; margin: calc(50% - 50px) auto; }
|
方式三
通过 定位+位移, 代码较多, 但是当宽度高度改变时不影响居中
支持行内元素的居中, 因为position使其变为定位元素, 可设置宽高
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| .outer { width: 500px; height: 500px; border: 1px solid black; position: relative; } .inner { width: 100px; height: 100px; background-color: purple; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
|
行内元素的居中
行内元素特点:
方式一
1 2 3 4 5 6 7 8 9 10 11 12
| .outer { width: 500px; height: 500px; border: 1px solid black; line-height: 500px; text-align: center; } .inner { background-color: purple; }
|
1 2 3 4
| <div class="outer"> <span class="inner"> CSS </span> </div>
|

方式二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <style> .outer { width: 500px; height: 500px; border: 1px solid black; line-height: 500px; text-align: center; } .inner { background-color: purple; vertical-align: middle; } </style>
<div class="outer"> <span class="inner"> CSS </span> </div>
|

行内元素:
水平基本考虑: text-algin:center;
垂直上设置行高与height属性同高: line-height