子元素左右垂直居中
1、子元素设置了高度和宽度
通过position设置子元素相对于父元素定位,然后将子元素的top、right、bottom、left设置成0
再将margin设置成auto,就实现了左右垂直居中
原理记住这个公式就行
水平布局:margin-left + left + width + right + margin-right = 父元素宽度
垂直:margin-top + top + height + bottom + margin-bottom = 父元素高度
在子元素高度确定的情况下,我们将top、right、bottom、left设置成0
margin设置成auto后,浏览器就会自动将剩余宽度平均分配给margin
代码:
<style>
.box1{
width: 200px;
height: 200px;
border: 1px solid red;
margin: 0 auto;
position: relative;
}
.box-son{
width: 50px;
height: 50px;
background-color: black;
/* 通过position设置子元素相对于父元素的位置,实现左右垂直居中 */
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
<body>
<div class="box1">
<div class="box-son"></div>
</div>
</body>
效果:
2、子元素没有设置高度和宽度
当子元素没有确定高度宽度时,就不能用上诉方法了,
因为浏览器会优先将宽度和高度分配给子元素的高度和宽度。
这种情况,我们可以先将子元素的left和top设置成50%,但是这不能居中
因为子元素本身的内容还占据一定的高度和宽度。
这时我们可以用transform: translateX(-50%) translateY(-50%);
将子元素本身向左向上偏移自身的50%,这样就达到了左右垂直居中的效果
代码:
<style>
.box1{
width: 200px;
height: 200px;
border: 1px solid red;
margin: 0 auto;
position: relative;
}
.box-son{
position: absolute;
left: 50%;
top: 50%;
/* 将自身向左向上平移50% */
transform: translateX(-50%) translateY(-50%);
}
</style>
<body>
<div class="box1">
<div class="box-son">子元素</div>
</div>
</body>
效果: