巧用 position:absolute
1、跟随性
下面这种方法更加简便以及更方便维护,
例如“西部世界”,由于不用将父元素设为position:relative,position:absolute的位置也就不用根据文字多少而重新进行top、left等位置的计算。
<div class="item1">西部世界<i></i></div> <div class="item2"> <i></i> <img src="images/orange.jpg" alt=""><!-- --><i></i> </div>
.item1 i { position: absolute; background: url(images/hot.png) 0 0 no-repeat; width: 30px; height: 16px; margin: -6px 0 0 2px; } .item2 i:nth-child(1) { position: absolute; background: url(images/free-appointment.png) 0 0 no-repeat; width: 56px; height: 56px; margin: 0; } .item2 i:nth-child(3) { position: absolute; background: url(images/flag_niuzhuan.jpg) 0 0 no-repeat; width: 64px; height: 20px; margin-left: -64px; overflow:hidden; text-indent: -9em; } /*如果用文字不用图片*/ /* .item2 i:nth-child(1) { position: absolute; line-height:20px; background-color: #f60; padding: 0 5px; font-size: 12px; color: #fff; } */
2、没有宽度没有高度,实现宽高满屏效果
上图是一个全屏的遮罩层,没有定义宽和高
<div class="mask"></div>
.mask { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: rgba(51, 51, 51,.5); }
position: absolute;top: 0;left: 0;width: 50%; == position: absolute;top: 0;left: 0;right: 50%;
实现距离右侧200像素的全屏自适应的容器层 position: absolute;left: 0;right: 200px;
但是width只能用css3 cale计算 position: absolute;left: 0;width: cale(100%-200px);
宽50%,上下铺满 width: 50%;position: absolute;top: 0;bottom: 0;
3、高度自适应布局
<div class="page"> <div class="list"></div> <div class="list"></div> <div class="list"></div> <div class="list"></div> <div class="list"></div> <div class="list"></div> <div class="list"></div> <div class="list"></div> <div class="list"></div> </div>
.page { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .list { background: #ECA7A5; width: 33.3%; height: 33.3%; border-radius: 50%; float: left; position: relative; }
4、如果尺寸限制、拉伸以及margin:auto;同时出现,就会出现绝对定位元素的绝对居中效果!
![](https://images2015.cnblogs.com/blog/818461/201611/818461-20161115231326435-1005154817.png)
<div class="item3"><img src="images/orange.jpg" alt=""></div>
.item3 { position: absolute; left: 0; right: 0; width: 200px; margin: auto; }