就像photoshop中的图层功能会把一整张图片分层一个个图层一样,网页布局中的每一个元素也可以看成是一个个类似图层的层模型。层布局模型就是把网页中的每一个元素看成是一层一层的,然后通过定位属性position对元素进行定位摆放,最终实现网页的布局。
定位属性position有4个值,分别是静态定位(static)、相对定位(relative)、绝对定位(absolute)和固定定位(fixed)。默认就是static。所以我们略过。
元素设置了定位以后,还要依靠4个方位属性来进行定位摆放。
方位属性:
top:让元素相对于指定目标的顶部偏移指定的距离。例如: top:10px; 表示距离顶部10像素right:让元素相对于指定目标的右边偏移指定的距离。例如: right:10px; 表示距离顶部10像素bottom:让元素相对于指定目标的底部偏移指定的距离。例如: bottom:10px; 表示距离顶部10像素left:让元素相对于指定目标的左边偏移指定的距离。例如: left:10px; 表示距离顶部10像素
相对定位(relative)
相对定位就是在正常文档流中,元素相对于自身位置使用left、right、top、bottom属性进行定位偏移。
.c1{width: 200px;height: 200px;background-color: indianred;}.c2{width: 200px;height: 200px;background-color: orange;position: relative;left: 200px;top: 200px;}.c3{width: 200px;height: 200px;background-color: lightblue;}
绝对定位(absolute)
绝对定位就是将元素脱离文档流,然后使用left、right、top、bottom属性相对于其最接近的一个具有定位属性的父级元素进行绝对定位,如果不存在这样的父级元素,则默认是相对于body元素进行绝对定位。
轮播图案例:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><style>*{margin: 0;padding: 0;}.lunbotu{width: 590px;height: 470px;border: 1px solid rebeccapurple;margin: 100px auto;position: relative;}.lunbotu ul{list-style: none;}.lunbotu .imgs li{z-index: 10;position: absolute;top: 0;left: 0;}.lunbotu .btn li{z-index: 20;position: absolute;}.lunbotu .btn .left_btn{left: 0;top: 50%;}.lunbotu .btn .right_btn{right: 0;top: 50%;}.lunbotu .btn div{width: 40px;height: 60px;background-color: #616161;color: white;text-align: center;line-height: 60px;border-radius: 15%;font-size: 20px;margin-top: -30px;}</style></head><body><div class="lunbotu"><ul class="btn"><li class="left_btn"> <div><</div> </li><li class="right_btn"> <div>></div> </li></ul><ul class="imgs"><li><a href=""><img src="https://img12.360buyimg.com/pop/s590x470_jfs/t1/178599/8/1142/28979/6087858aE1679d862/173e0cfa2612b705.jpg.webp" alt=""></a></li><li><a href=""><img src="https://imgcps.jd.com/ling4/6038430/5Lqs5Lic5aW954mp57K-6YCJ/MuS7tjjmipgz5Lu2N-aKmA/p-5bd8253082acdd181d02fa42/9ea6716c/cr/s/q.jpg" alt=""></a></li><li><a href=""><img src="imgs/1.jpg" alt=""></a></li></ul></div></body></html>
固定定位(fixed)
固定定位与绝对定位有点相似,但是固定定位是使用left、right、top、bottom属性相对于整个浏览器的窗口进行定位,而不再相对于某个HTML页面元素了,所以当元素使用了固定定位以后,就算页面的滚动条滚动了,固定定位的元素也不会变化位置。也就是说固定定位是相对于窗口的定位,不受文档流的影响了。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><style>.c1{height: 2000px;background-color: #616161;}.return_top{width: 160px;height: 80px;background-color: #336699;color: white;text-align: center;line-height: 80px;font-size: 20px;/*完全脱离文档流,参照物窗口*/position: fixed;right: 20px;bottom: 20px;}</style></head><body><div class="c1"></div><div class="return_top">返回顶部</div></body></html>
