垂直居中布局

居中的各种实现方案

html

1
2
3
<div class="parent">
<div class="child">DEMO</div>
</div>

水平居中布局的实现

(1) inline-block + text-align

1
2
3
4
5
6
.parent{
text-align: center;
}
.child{
display: inline-block;
}

(2) table + margin

1
2
3
4
.child{
display: table;
margin:0 auto;
}

(3) absolute + transform

1
2
3
4
5
6
7
8
.parent{
position:relative;
}
.child{
position:absolute;
left:50%;
transform:translateX(-50%);
}

(4) flex + justify-content

1
2
3
4
.parent{
display: flex;
justify-content: center;
}

垂直居中的实现

(1) table-cell + vertical-align

1
2
3
4
.parent{
display: table-cell;
vertical-align:middle;
}

(2) absolute + transform

1
2
3
4
5
6
7
8
.parent{
position:relative;
}
.child{
position:absolute;
top:50%;
transform:translateY(-50%);
}

(3) flex + align-items

1
2
3
4
.parent{
display: flex;
align-items: center;
}

居中(水平居中+垂直居中)

(1) inline-block+text-align + table-cell+vertical-align

1
2
3
4
5
6
7
8
.parent{
text-align:center;
display: table-cell;
vertical-align:middle;
}
.child{
display:inline-block;
}

(2) absolute + transform

1
2
3
4
5
6
7
8
9
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}

(3) flex + justify-content + align-items

1
2
3
4
5
.parent{
display: flex;
justify-content: center;
align-items: center;
}

垂直居中布局
https://jacksiongt.github.io/2021/04/30/csscenter/
作者
Jacksion
发布于
2021年4月30日
许可协议