CSS 实现元素水平和垂直居中的常用方法
XPoet 自由程序猿

Flexbox 布局

  • 父容器使用 Flexbox 布局实现子元素的水平和垂直居中。

    1
    2
    3
    4
    5
    .container {
    display: flex;
    align-items: center; /* 实现垂直居中 */
    justify-content: center; /* 实现水平居中 */
    }
  • 结合 Flexbox 和 margin: auto; 属性实现水平和垂直居中。

    1
    2
    3
    4
    5
    6
    7
    .container {
    display: flex;
    }

    .child {
    margin: auto; /* 同时实现水平和垂直居中 */
    }

Grid 布局

父容器使用 Grid 布局实现子元素的水平和垂直居中。

1
2
3
4
.container {
display: grid;
place-items: center; /* 同时实现水平和垂直居中 */
}

Table 属性

使用 Table 属性实现水平和垂直居中。

1
2
3
4
5
6
7
8
9
10
11
12
13
.container {
width: 100px;
height: 100px;
display: table-cell;
vertical-align: middle; /* 实现垂直居中 */
text-align: center; /* 实现水平居中 */
}

.child {
width: 20px;
height: 20px;
display: inline-block;
}

子绝父相

子绝父相表示:子元素设置绝对定位,父容器设置相对定位。

不知道子元素和父容器的高度

使用 position 和 transform 属性可以同时实现水平和垂直居中。

1
2
3
4
5
6
7
8
9
10
.container {
position: relative;
}

.child {
position: absolute;
top: 50%; /* 实现垂直居中 */
left: 50%; /* 实现水平居中 */
transform: translate(-50%, -50%);
}

知道子元素和父容器的高度

使用 position 和 margin 属性同时实现水平和垂直居中。

1
2
3
4
5
6
7
8
9
10
11
12
13
.container {
position: relative;
height: 100vh;
}

.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; /* 同时实现水平和垂直居中 */
}

line-height

如果子元素是单行文本,可以使用 line-height 来实现垂直居中。

1
2
3
4
5
.container {
height: 100px;
text-align: center; /* 实现水平居中 */
line-height: 100px; /* 实现垂直居中 */
}

这个方法适用于只包含单行文本的元素。

 Comments
Comment plugin failed to load
Loading comment plugin