☊【实现要求】:父元素包含子元素,子元素垂直居中布局
<div class="demo5">
<div class="child">A</div>
</div>
√【实现】:
♪ 子元素 A 宽高已知,相对于父元素水平垂直居中
① position: absolute
布局
*基于自身高度/宽度偏移的缺点:若宽度/高度改变,则偏移会改变,不会持续保持居中
.demo5 {
$px;
height: $px;
position: relative; // 定位父元素
.child {
400px;
height: 50px;
position: absolute; // 相对于父元素定位
top: 50%; // 使用百分比定位
left: 50%; // 使用百分比定位
margin-top: -25px; // 向上偏移自身高度的一半
margin-left: -250px; // 向左偏移自身宽度的一半
}
}
♫ 子元素 A 宽高未知,相对于父元素水平垂直居中
② position: absolute
布局
.demo5 {
$px;
height: $px;
position: relative; // 定位父元素
.child {
$px;
height: $px;
position: absolute; // 相对于父元素定位
margin: auto; // 上下左右margin都自适应
top: 0;
bottom: 0;
left: 0;
right: 0;
}
}
③ position: absolute
+ CSS3
布局
.demo5 {
$px;
height: $px;
position: relative; // 定位父元素
.child {
$px;
height: $px;
position: absolute; // 相对于父元素定位
top: 50%; // 使用百分比定位
left: 50%; // 使用百分比定位
transform: translate(-50%, -50%); // 向X轴/Y轴偏移自身宽度/高度的一半
-webkit-transform: translate(-50%, -50%);
}
}