在css布局中,块级元素的水平垂直居中是非常常见的需求,这篇文章针对块级元素的水平垂直居中的方法进行了一些讨论,不足之处欢迎指正,也欢迎大家提出自己的意见与看法ovo~
国际惯例(战术搞笑),让我们先来看一下效果图:
- 01 margin居中
.father{
width: 400px;
height: 400px;
background-color: #1e1e1e;
overflow: hidden;
}
.son{
width: 200px;
height: 200px;
background-color: #c1acae;
margin-top: 100px;
margin-left: 100px;
}
<div class="father">
<div class="son"></div>
</div>
父盒子的高度是400px,子盒子的高度是200px,为了达到居中效果,子盒子需要距离父盒子的上边距100px,水平方向同理,此方法的缺陷是容易出现塌陷问题,给父盒子加上overflow:hidden即可,如果自己不想计算,也可以借助计算值来完成计算的步骤
.father{
width: 400px;
height: 400px;
background-color: #1e1e1e;
overflow: hidden;
}
.son{
width: 200px;
height: 200px;
background-color: #c1acae;
margin-top: calc((400px - 200px)/2);
margin-left: calc((400px - 200px)/2);
}
- 02 绝对定位+transform居中
.father{
width: 400px;
height: 400px;
background-color: #1e1e1e;
position: relative;
}
.son{
width: 200px;
height: 200px;
background-color: #c1acae;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
<div class="father">
<div class="son"></div>
</div>
此方法的基本原理是定位中的子绝父相,如果布局需要,子绝父绝也可以达到一样的效果,left和top是相对于父元素的大小来移动的,移动之后会稍微偏右偏下,所以再加一句transform移动自身的一半来进行修正,就可以达到一个比较完美的居中效果
- 03 绝对定位+margin auto
.father{
width: 400px;
height: 400px;
background-color: #1e1e1e;
position: relative;
}
.son{
width: 200px;
height: 200px;
background-color: #c1acae;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
<div class="father">
<div class="son"></div>
</div>
用margin均匀的周围的范围挤开
- 04 flex布局
<div class="father">
<div class="son"></div>
</div>
.father{
width: 400px;
height: 400px;
background-color: #1e1e1e;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 200px;
height: 200px;
background-color: #c1acae;
}
将父元素设置为弹性容器,flex的center布局会将弹性盒子居中,此方法不仅适用于div,对于其他的元素也生效,在flex布局中,没有块级元素和行内元素的区分
- 05 栅格布局居中
.father {
width: 600px;
height: 600px;
background-color: #1e1e1e;
display: grid;
grid-template-rows: 1fr 1fr 1fr;
grid-template-columns: 1fr 1fr 1fr;
}
.son {
width: 200px;
height: 200px;
background-color: #c1acae;
grid-row-start: 2;
grid-row-end: 3;
grid-column-start: 2;
grid-column-end: 3;
}
栅格布局的本质就是把整个父盒子分成一个均等的九宫格(当然只要你喜欢也可以设置5* 5,7 * 7,任何你喜欢或者需要的尺寸),然后把子元素放置在最中间的栅格里
- 06 表格布局居中
.father {
width: 400px;
height: 400px;
background-color: #1e1e1e;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son {
width: 200px;
height: 200px;
background-color: #c1acae;
display: inline-block;
}
严格意义上来说此方法不算标准的块级元素居中,他将子盒子的显示方式声明为了行内块,但是此方法涉及到了与上面截然不同的布局方式,放在最后算作权当一个拓展补充参考
本文只对块级盒子div的居中进行了探讨,关于文本居中和行内元素的居中不一定适用哦:)