1 绝对定位 + 转换
绝对定位 + 转换
.parent {
position: relative;
width: 400px;
height: 400px;
background: skyblue;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background: pink;
}

2 弹性模型
弹性模型
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 400px;
background: skyblue;
}
.child {
width: 200px;
height: 200px;
background: pink;
}

3 单元格方式
单元格方式
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 400px;
height: 400px;
background: skyblue;
}
.child {
display: inline-block;
width: 200px;
height: 200px;
background: pink;
}

本文介绍了三种实现元素在父容器内水平垂直居中的CSS方法:使用绝对定位配合转换,利用弹性盒子模型,以及采用单元格显示方式。每种方法都附带了具体的CSS样式代码。

2876

被折叠的 条评论
为什么被折叠?



