在项目中经常会遇到设置元素水平垂直居中的需求。而且具体的场景也不同,所以将个人总结的方法做个汇总,希望对浏览者有用。
以下所举的例子都以一个html为准,这里规定好一些公用样式。
body {
background-color: #efefef;
}
main {
background-color: #fff;
padding: 10px;
margin:10px 0px;
}
main p {
background-color: #aaf;
}举例如下:
.parent1 {
text-align:center;
}
.child1 {
display:inline|inline-block;
}<main class="parent2">
<p class="child2">我是孩子2,我要水平居中</p>
</main>
.child2 {
width:60%;
margin:auto;
}<main class="parent4">
<p class="child4">我是孩子4,我要水平居中</p>
<p class="child4">我是孩子4,我要水平居中</p>
<p class="child4">我是孩子4,我要水平居中</p>
</main>
.parent4 {
display: flex;
justify-content: center;
}
.child4 {
margin:10px;
}将line-height和height的值设置为相同值,
<main class="parent5">
<p class="child5">我是孩子5,我要垂直居中</p>
</main>
.child5 {
height:50px;
line-height: 50px;
}<main class="parent6">
<p class="child6">我是孩子6,我要垂直居中</p>
<p class="child6">我是孩子6,我要垂直居中</p>
<p class="child6">我是孩子6,我要垂直居中</p>
</main>
.parent6 {
display: table;
}
.child6 {
display: table-cell;
border:2px solid #000;
vertical-align: middle;
}<main class="parent7">
<p class="child7">我是孩子7,我要垂直居中</p>
</main>
/*如果知道子元素宽高*/
.parent7 {
position: relative;
height: 100px;
}
.child7 {
position: absolute;
top:50%;
height:60px;
margin-top:-30px;
}
/*如果不知道子元素宽高*/
.parent7 {
position: relative;
height: 100px;
}
.child7 {
position: absolute;
top:50%;
transform: translateY(-50%);
}<main class="parent8">
<p class="child8">我是孩子8,我要垂直居中</p>
</main>
.parent8 {
height: 200px;
display: flex;
flex-direction: column;
justify-content: center;
}<main class="parent9">
<p class="child9">我是孩子9,我要水平垂直居中</p>
</main>
/*如果不知道子元素宽高*/
.parent9 {
position: relative;
height: 150px;
}
.child9 {
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
/*如果知道子元素宽高*/
.parent9 {
position: relative;
height: 150px;
}
.child9 {
position: absolute;
top:50%;
left:50%;
height:60px;
width:100px;
margin-left:-50px;
margin-top:-30px;
}.parent10 {
height: 200px;
display: flex;
flex-direction: column;
justify-content: center;
}
.child10 {
margin: auto;
}

更多css 水平垂直居中的方法总结相关文章请关注PHP中文网!
立即学习“前端免费学习笔记(深入)”;
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号