flex
.parent {
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 如果也需要水平居中 */
}
grid
.parent {
display: grid;
align-items: center; /* 垂直居中 */
justify-content: center; /* 如果也需要水平居中 */
}
.parent {
position: relative; /* 父元素需设置相对定位 */
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%); /* 垂直居中 */
}
margin:auto
.parent {
position: relative;
}
.child {
position: absolute;
height: 200px; /* 必须设置固定高度 */
top: 0;
bottom: 0;
margin: auto; /* 上下自动外边距实现居中 */
}
居中行内元素
.parent {
height: 100px;
line-height: 100px; /* 与高度值相同 */
}
table
.parent {
display: table;
height: 100%; /* 通常需要显式设置高度 */
}
.child {
display: table-cell;
vertical-align: middle;
}