
元素水平垂直居中是 web 开发中常见遇到的问题
这个组合,常用于图片的居中显示,子元素设置绝对定位,父级元素相对定位,也可以将父元素 ·wrapper的相对定位,移入子元素img中,替换掉绝对定位。效果也是一样的
html 示例代码
<div class="wrapper">
<img src="test.png" />
</div>
css 示例代码
.wrapper {
width: 100%;
height: 300px;
border: 1px solid #ccc;
position: relative;
}
.wrapper > img {
position: absolute; // 子元素绝对定位
left: 50%; // left值50%
top: 50%; // top值50%
transform: translate(
-50%,
-50%
); // 利用transform变换,translate平移,水平,垂直方向上
}
利用 table的单元格居中效果展示。与 flex一样,需要写在父级元素上
<div class="wrapper">
<p>itclanCoder元素水平垂直居中</p>
</div>
css代码
.wrapper {
width: 100%;
height: 300px;
border: 1px solid #ccc;
display: table-cell;
text-align: center;
vertical-align: middle;
}
在实际开发中,很多元素的高度,宽度是不固定的,随着自身的内容撑大而撑大的,怎么让它在页面中实现水平垂直居中显示呢?
html 标签
<div class="wrapper flex-center">
<p>itclanCoder元素水平垂直居中</p>
</div>
css 层叠样式
.wrapper {
width: 100%;
height: 300px;
border: 1px solid #ccc;
}
.flex-center {
//在父级元素中,添加如下代码即可
display: flex;
justify-content: center; // 水平居中
align-items: center; // 垂直居中
}
更多元素水平垂直居中https://coder.itclan.cn/fontend/css/css-base-elem-center/