块元素的居中

块元素特点:

  • 宽度撑满父元素
  • 高度由内容撑开
  • 可设置宽高
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中, 垂直水平居中?

image-20230326155510307

方式一#

通过flex布局, 首选, 无需计算, 简单

支持行内元素, 行内块元素的居中, 因为flex布局后, 其子元素默认变为块元素

image-20230326155619103

方式二#

较简洁, 但是需要简单的计算, 且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;
/* 父元素的50%, 减去自身高度的一半50px */
/* 注意margin塌陷问题, 这里因为父元素有border, 所以未塌陷 */
/* calc中的符号两侧必须有空格!!! */
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;
/* 行高与height同高, 垂直居中 */
line-height: 500px;
/* text-algin 不只可以让文字居中, 还可以让行内元素,行内块元素居中 */
text-align: center;
}
.inner {
background-color: purple;
}
1
2
3
4
<div class="outer">
<!-- 因为inline元素不能设置宽高, 只能通过内容撑开, 所以这里写点东西 -->
<span class="inner"> CSS </span>
</div>

image-20230326162213852

方式二#

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;
/* 行高与height同高, 垂直居中 */
line-height: 500px;
/* text-algin 不只可以让文字居中, 还可以让行内元素,行内块元素居中 */
text-align: center;
}
.inner {
background-color: purple;
vertical-align: middle;
}
</style>

<div class="outer">
<!-- 因为inline元素不能设置宽高, 只能通过内容撑开, 所以这里写点东西 -->
<span class="inner"> CSS </span>
</div>

image-20230326162733744

行内元素:

水平基本考虑: text-algin:center;

垂直上设置行高与height属性同高: line-height