提示:本文总结了在工作中常用的4种块级元素水平垂直居中方法,希望对你有所帮助
一、使用flex布局(无敌)
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
<style>
.father {
width: 300px;
height: 300px;
border: 2px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 100px;
height: 100px;
background-color: #ccc;
}
</style>
效果图:
此方法是本鹅工作中最常用的也是最好用的,推荐大家使用!
对flex布局有兴趣研究的伙伴可以参考阮一峰大佬的博客:
Flex 布局教程:语法篇 - 阮一峰的网络日志
二、使用定位(子绝父相) + css3的translate平移属性
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
<style>
// 效果图同一
.father {
width: 300px;
height: 300px;
border: 2px solid red;
position: relative;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%; // top:50% left:50% 之后,此时子盒子的左上角顶点处于父盒子的中心位置
transform: translate(-50%,-50%); // 平移子盒子自身的50%即可
background-color: #ccc;
}
</style>
效果图同一
三、使用定位(子绝父相)+ margin: auto
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
<style>
.father {
width: 300px;
height: 300px;
border: 2px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
}
</style>
注意:
1、margin: auto是具有强烈计算意味的关键字,用来分配元素对应方向上的剩余空间。例如margin:10px,等同于margin-top:10px;margin-left:10px;margin-right:10px;margin-bottom:10px
2、不使用定位的情况下,margin:auto 只能使块级元素水平居中,不能实现垂直居中,因为垂直方向上默认没有剩余的空间。即margin: auto = margin: 0 auto
3、有了绝对定位后,margin-top和margin-bottom 的值就不是0了,也是通过计算所得。所以可以实现垂直居中
四、 flex布局 + margin: auto
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
<style>
.father {
width: 300px;
height: 300px;
border: 2px solid red;
display: flex;
}
.child {
width: 100px;
height: 100px;
margin: auto;
background-color: #ccc;
}
</style>
效果图同一
此方法是代码量最少的一个,原理类似方法三
更多推荐
CSS块级元素水平垂直居中常用的几种方式
发布评论