网页常见布局方式
使用定位
相对定位
position: relative
left: 100px;
top: 100px;
Tips: 如果 4 个定位都有,以 top 和 left 为准
绝对定位
position: absolue
left: 100px;
top: 100px;
固定定位
元素层级关系
案例:子盒子在父盒子中水平居中
<style>
.box-wrap {
position: relative;
width: 500px;
height: 500px;
background-color: skyblue;
}
.box {
position: absolute;
left: 50%;
top: 50%;
/* 手动计算盒子的一半 */
margin-left: -150px;
margin-top: -150px;
width: 300px;
height: 300px;
background-color: pink;
}
</style>
<div class="box-wrap">
<div class="box"></div>
</div>
<style>
.box-wrap {
position: relative;
width: 500px;
height: 500px;
background-color: skyblue;
}
.box {
position: absolute;
left: 50%;
top: 50%;
/* 移动自身一半 */
transform: translate(-50%, -50%);
width: 300px;
height: 300px;
background-color: pink;
}
</style>
<div class="box-wrap">
<div class="box"></div>
</div>