时间:2021-07-01 10:21:17 帮助过:29人阅读
下面四种方案都是能够实现,当父元素或子元素的宽高发生改变时,依旧维持水平垂直居中布局的方案。
html
<p class="father">
<p class="son"></p>
</p>css
.father {
position: relative;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: red;
}html不变
<p class="father">
<p class="son"></p>
</p>css
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 100px;
height: 100px;
background: red;
}需要设置父元素为display:table-cell,利用vertical和text-align可以让所有的行内块级元素水平垂直居中
给子元素设置 display: inline-block
html 不变
<p class="father">
<p class="son"></p>
</p>css
.father {
display: table-cell;
width: 200px;
height: 200px;
background: skyblue;
vertical-align: middle;
text-align: center;
}
.son {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}html不变
<p class="father">
<p class="son"></p>
</p>css不变
.father {
display: grid;
align-items:center;
justify-content: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 10px;
height: 10px;
border: 1px solid red
}相关推荐:
html的元素水平垂直居中应该怎么设置
css如何实现水平垂直居中以及两端对齐的代码分享
CSS实现水平垂直居中的几种方法介绍
以上就是css水平垂直居中的4种实现方法的详细内容,更多请关注Gxl网其它相关文章!