0.脱离标准文档流
绝对定位的元素会脱离标准文档流,拥有z-index属性,并且对于它的任何操作和改变都不会影响它的兄弟元素和父级元素,这里就不过多介绍。
不过值得注意的是,虽然绝对定位元素脱离的标准文档流,但是它依然会受到父元素影响哦,比如line-height和text-align属性等。
1.跟随性
绝对定位的元素脱离标准文档流之后,并不是跑到了任意的位置,而是跟在前一个没有添加absolute或者fixed值的元素后面或者下面。
不过在设置了left/top/bottom/right这些值之后,它相对位置的参照元素便是离它最近的定位(absolut/fixed/relative)元素
2.触发BFC效果
绝对定位的元素会触发BFC效果,使得inline元素也能让宽高和垂直margin生效。
3.具体用处
通过设置top、right、bottom、left四个值大小,调整元素距离四个方向的值,使得元素拉伸,来实现我们想要的效果。
0.left/right与width
绝对定位元素,left/right可以和width同时存在,不过最终元素宽度为width值。
给绝对定位元素同时设置left: x; right: x后,其效果更像是给绝对定位元素添加了一个虚拟不存在的父元素。
比如有一个绝对定位元素div,div设置 left: 0; right: 0,则div便多了一个width: 100%的虚拟不存在的父元素,而div的宽度便是100%,如果给div再设置一个width属性,那么div的宽度便等于width值了,这时给div添加margin:0 auto; 便能让div居中。
<div class="page">
包裹元素
<div class="backTop">设置了width值的绝对定位元素</div>
</div>
.page {
width: 800px;
height: 1000px;
background-color: #ccc;
margin: 0 auto;
}
.backTop {
width: 100px;
height: 200px;
background-color: #f34;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
}
1.实现全屏遮罩效果
<div class="wrap">
这是一个半透明遮罩
</div>
* {margin: 0; padding: 0;}
.wrap {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,.5);
color: #fff;
}
2.使用absolute实现fixed效果
在移动端,使用fixed布局,有时候会遇到一些位置跳动的问题,这个时候通常可以使用absolute来代替实现,解决问题
<div class="wrap">
<div class="main">
<ul class="list">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</div>
<div class="footer">
这里是底部
</div>
</div>
* {margin: 0; padding: 0;}
html, body {
height: 100%;
}
.wrap {
height: 100%;
overflow: auto;
}
.item {
height: 70px;
margin-bottom: 10px;
background-color: #ccc;
}
.footer {
position: absolute;
left: 0;
right: 0;
bottom: 0;
background-color: #5a3;
}
3.宽高自适应的九宫格效果
这是从张鑫旭大哥的文章里看见的,虽然没用过这种布局,不过感觉挺不错的
<div class="page">
<div class="list" data-index="1"></div>
<div class="list" data-index="2"></div>
<div class="list" data-index="3"></div>
<div class="list" data-index="4"></div>
<div class="list" data-index="5"></div>
<div class="list" data-index="6"></div>
<div class="list" data-index="7"></div>
<div class="list" data-index="8"></div>
<div class="list" data-index="9"></div>
</div>
html, body { height: 100%; margin: 0; }
.page {
position: absolute;
left: 0; top: 0; right: 0; bottom: 0;
}
.list {
float: left;
height: 33.3%; width: 33.3%;
position: relative;
}
.list:before {
content: '';
position: absolute;
display:block;
/*height:100%;*/
/*width:100%;*/
left: 10px; right: 10px; top: 10px; bottom: 10px; /* 这里通过设置left、right、top、bottom来拉伸元素,如果设置height和width属性,则会优先使用width和height */
border-radius: 10px;
background-color: #cad5eb;
}
.list:after {
content:attr(data-index);
position: absolute;
height: 30px;
left: 0; right: 0; top: 0; bottom: 0;
margin: auto;
text-align: center;
font: 24px/30px bold 'microsoft yahei';
}