水平布局:
left + margin-left + border- left + padding-left + width + padding-right + border-right + margin-right + right
当我们开启绝对定位后:
水平方向的布局等式就需要多添加left 和right 两个值
此时规则和之前一样只多了两个值
当发生过度约束:
如果9个值中没有auto 则自动调整right 的值以使等式成立
如果有auto, 则自动调整auto的值来使得等式满足
此时自动调整right 使得等式成立,因此right为负200
<style>
.box1{
position: relative;
width: 200px;
height: 200px;
background-color: burlywood;
}
.box2{
position:absolute;
width: 100px;
height: 100px;
background-color: cadetblue;
left: 300px;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
可设置auto的值margin width left right
因为left 和right的值默认是auto ,所以如果不知道left 和right, 则不等式不满足时,会自动调整这两个值。
所以要设置 left = 0; right = 0; 才能调整margin-left和margin-right,否则会自动调整left和right。给margin-left、margin-right设置值会失效。
水平方向居中:
<style>
.box1{
position: relative;
width: 200px;
height: 200px;
background-color: burlywood;
}
.box2{
position:absolute;
width: 100px;
height: 100px;
background-color: cadetblue;
left : 0;
right: 0;
margin-left :auto;
margin-right: auto;
}
</style>
效果为:
垂直方向布局
垂直方向布局等式也必须满足 :
top + margin-top/bottom + padding-top / bottom + border-top/bottom + height = 包含块的高度
过度约束则调整bottom的值
垂直居中(绝对定位后才可设置):
设定height为固定值,margin-top = auto 、margin-bottom = auto
代码为:
<style>
.box1{
position: relative;
width: 200px;
height: 200px;
background-color: burlywood;
}
.box2{
position:absolute;
width: 100px;
height: 100px;
background-color: cadetblue;
/* left : 0;
right: 0; */
/* margin-left :auto;
margin-right: auto; */
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
效果为:
水平垂直双居中
在包含块的水平方向和垂直方向居中(位于中心)
注意: 是在包含块中间,包含块为根元素则为网页中间
margin=0
left = 0
right = 0
top = 0
bottom = 0
<style>
.box1{
position: relative;
width: 200px;
height: 200px;
background-color: burlywood;
}
.box2{
position:absolute;
width: 100px;
height: 100px;
background-color: cadetblue;
left : 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
/*或 margin-left :auto;
margin-right: auto;
margin-top: auto;
margin-bottom: auto; */
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
元素的层级
对于开启了定位元素, 可以通过z-index 属性来指定元素的层级
z-index需要一个整数作为参数, 值越大的层级越高,元素的层级越高,越优先显示
如果元素的层级一样,则优先显示靠下的元素
注意:祖先元素的层级再高也不会盖住后代元素。
z-index: 3;