CSS基础(19)_绝对定位元素的水平或垂直布局
文档流中布局
一个元素在其父元素中,水平布局之前是要满足以下等式: margin-left+border-left+padding-left+width+padding-right+border-right+margin-right=父元素内容区的宽度。
绝对定位元素布局
绝对定位元素的水平方向布局: 当我们开启了绝对定位后,此时脱离文档流相对于包含块布局,水平方向的布局等式就需要添加left和right两个值:left+margin-left+border-left+padding-left+width+padding-right+border-right+margin-right+right=包含块内容区的宽度。
绝对定位元素的垂直方向布局: 同理,垂直方向布局的等式也必须要满足:top+margin-top/bottom+padding-top/bottom+border-top/bottom+heigh=包含块内容区的高度。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/position_element_layout.css">
<title>绝对定位元素的水平和垂直布局</title>
</head>
<body>
<div class="box1">
<div class="box2"> </div>
</div>
</body>
</html>
.box1{
width: 150px;
height: 150px;
background-color:cadetblue;
position:relative;
}
/* 此时right值默认为70px */
.box2{
width: 60px;
height: 60px;
background-color:darkgreen;
position:absolute;
left: 20px;
}
过度约束: 当发生过度约束(9个值加一起不满足等式)时,如果9个值中没有auto则自动调整right值以使等式满足,如果有auto,则自动调整auto的值以使等式满足。可设置auto的值:margin width height left right
居中设置: 设置居中,当margin-left/right和margin-top/bottom值为auto时,left/right或top/bottom必须设置为0,因为left/right和top/bottom值默认是auto,如果不指定,则等式不满足时会自动调整这两个值。
/* 如果不设置left和right值,则不能正常居中显示*/
.box2{
width: 60px;
height: 60px;
background-color:darkgreen;
position:absolute;
margin-left: auto;
margin-right: auto;
left: 0px;
right: 0px;
}
同理,垂直方向也一样,设置margin-top、bottom-bottom为auto,top、bottom为0px。那么垂直水平居中呢?
.box2{
width: 60px;
height: 60px;
background-color:darkgreen;
position:absolute;
margin: auto;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
