本文主要和大家分享css水平垂直居中的4种实现方法,方案中我也给了宽高,但并不是说宽高固定了。而是以为不给宽高无法看到效果。这个方案不固定宽高的是指,用这个方案之后,如果你父元素、子元素的宽高发生了改变,依旧可以保证是水平垂直居中的位置。
下面四种方案都是能够实现,当父元素或子元素的宽高发生改变时,依旧维持水平垂直居中布局的方案。
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
}相关推荐:
以上就是css水平垂直居中的4种实现方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号