这篇文章给大家介绍的内容是关于CSS中常见的水平垂直居中的实现方法有哪些?CSS中三种常见的水平垂直居中,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
当不知道子元素的宽和高的时候,如何实现子元素的水平垂直居中,这里总结了几种方法:
HTML和CSS代码如下:
<div class="super-div">
<div class="sub-div">利用定位和transform
<br/>实现水平垂直居中</div>
</div>
.super-div {
width: 400px;
height: 300px;
border: 1px solid black;
}
.sub-div {
background-color: green;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* top left 分别相对于父元素的高度和宽度,translate相对于自身的宽度和高度 */
}这种实现方式的核心在于注释部分,相对定位的时候,top和left都是相对于父元素的高度和宽度计算,而transform是相对与自身宽高计算; 效果如下:
HTML和CSS代码实现如下:
<div class="super-div table">
<div class="table-cell">利用table-cell
<br/>实现水平垂直居中</div>
</div>
.super-div {
width: 400px;
height: 300px;
border: 1px solid black;
}
.table {
display: table;
}
.table-cell {
display: table-cell;
/*垂直居中*/
vertical-align: middle;
/*水平居中*/
text-align: center;
background-color: green;
}父元素设置table布局,子元素设置为table-cell布局。然后实现子元素的垂直水平居中,效果如下:
立即学习“前端免费学习笔记(深入)”;
HTML和CSS代码如下:
<div class="super-div flex">
<div class="flex-center">利用flex布局
<br/>实现水平垂直居中</div>
</div>
.super-div {
width: 400px;
height: 300px;
border: 1px solid black;
}
.flex {
display: flex;
/*flex布局*/
justify-content: center;
/*使子项目水平居中*/
align-items: center;
/*使子项目垂直居中*/
}
.flex-center {
background-color: green;
}实现效果如下:
相关文章推荐:
以上就是CSS中常见的水平垂直居中的实现方法有哪些?CSS中三种常见的水平垂直居中的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号