以下是六种常见的方法来将一个div水平垂直居中:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /* 子元素高度的一半 */
margin-left: -50px; /* 子元素宽度的一半 */
}
.parent {
display: grid;
place-items: center;
}
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
以上是六种常见的方法,你可以根据需要选择其中一种适合你的布局。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:div水平垂直居中的六种方法