CSS 系列之div 居中

div 内的元素水平垂直居中。

接下来,我们就来看看 div 在高度已知,高度未知的情况下,如何进行水平垂直居中。

我们先来看看两段 html 代码,解释下面的内容居中和元素居中。

  • 内容居中
1
<div class="box">我是内容</div>
  • 元素居中
1
2
3
<div class="box">
<div class="content">我是内容</div>
</div>

高度已知

div 内容居中

首先是内容,直接写在 div 中的,无嵌套任何元素。

  • 用于内容居中
1
2
3
4
5
6
7
8
.box {
width: 300px;
height: 300px;
background-color: #efcca1;
color: #fff;
text-align: center; /* 水平居中 */
line-height: 300px; /* 垂直居中 */
}

我们设置行高与高度相等时,可以设置对 line-height 进行设置,就可以进行垂直居中,然后使用 text-align 就可以进行水平居中。

当然,我们还是需要来看结果.

div-center1

其实这种方式,也可以用于元素居中,但是如果外部元素有其他内容时就会出错。我们来看一下

首先是内部只有一个元素时。

1
2
3
.content {
background-color: #1890ff;
}

div-center2

然后我们来看看内部还有其他元素时。

1
2
3
4
<div class="box">
其他元素
<div class="content">我是内容</div>
</div>

div-center3

所以不建议使用在元素居中的情况下。

position

绝对定位当然是要用在元素居中的情况了,需要使用内部元素进行偏移。

  • 用于元素居中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.box {
width: 300px;
height: 300px;
background-color: #efcca1;
position: relative;
}
.content {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}

div-center4

从结果来看,我们是可以进行居中的。

  1. 首先我们通过设置父元素 position: relative,然后在子元素中设置 position: absolute
  2. 我们对子元素进行偏移,top 50%left 50%,当然偏移之后,其实不是居中的。
  3. 我们在对其这是 margin 将以往 top 以及 left 方向挤压,居中。

高度未知

flex 居中

首先,当然要说一下,我们最常见的 flex 布局的居中了

  • 用于内容或者元素居中

我们来看看 flex 怎么居中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.box {
width: 300px;
height: 300px;
background-color: #efcca1;
display: flex;
justify-content: center;
align-items: center;
}
.content {
width: 100px;
height: 100px;
background-color: #1890ff;
color: #fff;
}

我们就可以看到结果了。

div-center5

偏移居中

我们需要设置一个相对定位进行偏移,然后使用 transform,往回偏移一个元素的一半宽度。

  • 用于元素居中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.box {
width: 300px;
height: 300px;
background-color: #efcca1;
}
.content {
width: 100px;
height: 100px;
background-color: #1890ff;
position: relative;
top: 50%; /* Y 偏移 50% */
left: 50%; /* X 偏移 50% */
transform: translate(-50%, -50%); /* x ,y 分别往回偏移元素的一半宽度 */
color: #fff;
}

我们可以看到结果跟 flex 布局是相同的。

div-center6

table-cell

设置 table-cell 之后,可以设置 vertical-align: middle 进行垂直居中设置。

  • 用于内容居中
1
2
3
4
5
6
7
8
9
.box {
width: 300px;
height: 300px;
background-color: #efcca1;
display: table-cell;
text-align: center;
vertical-align: middle;
color: #fff;
}

div-center7


居中方式,大体都介绍了一遍,如果后续发现新方式,可以评论我,让我加一加,谢谢各位。

-------------------- 本文结束 感谢阅读 --------------------