通过一些例子来简单了解这三种定位
相对定位(position: relative)
以自身为参照物,通过对top、bottom、left、right属性的设置来实现元素的偏移。left为正表示从该元素的左边向该元素中心偏移,其余三个可以类比得出。下图中代码实现了鼠标悬停在该元素时,向右上方微微抖动。也常被用作绝对定位元素的目标元素。
.pic-box ul li:hover{
/* 相对定位的目标就是它自己 */
/* 往中心方向偏移是正数,往非中心方向偏移是负数 */
position: relative;
left: 2px;
top: -2px;
}
绝对定位(position: absolute)
相对于最靠近的已定位祖先元素,或者是标签或标签定位,同样需要设置top、bottom、left、right这些属性。
.pic-box ul li{
/* 作为绝对定位的目标 */
position: relative;
border: 1px solid red;
margin: 10px;
padding: 10px;
background-color: rgb(204,204,204);
}
.pic-box p{
/* 绝对定位 */
position: absolute;
bottom: 40px;
text-align: center;
color: white;
}
效果(p标签相对于目标元素(对应父容器元素)向上偏移了40px):
固定定位(position: fixed)
相对于浏览器窗口的偏移,也需设置四个属性。可以用来实现回到页面顶部这样的操作。
.jump-top{
width: 100px;
height: 30px;
border: 1px solid red;
/* 固定定位,目标是屏幕 */
position: fixed;
right: 20px;
bottom: 20px;
}
<div class="jump-top">
<a href="#">回到顶部</a>
</div>
效果: