目录
定位positon,相较于浮动,能够更好地调节元素的位置,其拥有五个属性值
包括默认定位 static、相对定位 relative 、绝对定位 absolute、固定定位 fixed以及粘性定位 sticky
.box{
position: relative; /*相对于自身原有位置移动*/
position: absolute; /*相对于父对象移动*/
position: fixed; /*固定于视窗上,不会随着页面的上下移动而移动*/
position: static; /*默认值,没有任何影响*/
position: sticky; /*完全位于视窗中时,同相对定位,但当页面移动,
直至对象边 缘触及视窗的边缘,就会固定于视窗上*/
/*宽高、背景、字体等其他属性*/
}
1.1 默认定位(position:static)
元素的默认定位方式,即标准流,一般不使用,但也可以用于某些场合下,取消元素的其他定位,例如:
.father{
width: 150px;
height: 150px;
background: skyblue;
}
.father .son{
position: absolute; /*绝对定位*/
top: 50px; /*从父对象的顶部向下移动50px的距离*/
width: 50px;
height: 50px;
background-color: pink;
}
.father:hover .son{
position: static; /*鼠标移到.father上时,取消.son先前设置的
绝对定位,使其重新回到左上角默认位置*/
}
<div class="father">
<div class="son"></div>
</div>
1.2 相对定位(position:relative)
相对于 元素原先在标准流中的位置 移动,
元素本身未“脱标”,还占据着原来的空间位置,你可以想象成仅仅是把可见的部分移动了,而基础不动。
.father{
width: 250px;
height: 250px;
background: skyblue;
}
.father .son1{
position: relative; /*相对定位*/
top: 75px; /*从原有位置自上而下移动75px的距离*/
left: 75px; /*从原有位置自左向右移动75px的距离*/
width: 50px;
height: 50px;
background-color: pink;
}
.son2{
width: 50px;
height: 50px;
background-color: green;
}
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
1.3 绝对定位(position:absolute)
相对于 祖先元素 移动
元素“脱标”,不再占据任何空间
.father{
width: 250px;
height: 250px;
background: skyblue;
position: relative; /*相对定位*/
}
.father .son1{
position: absolute; /*绝对定位*/
bottom: 50%; /*从父对象的底部开始向上移动相当于父元素50%宽度的距离*/
right: 50%; /*从父对象的右侧开始向左移动相当于父元素50%宽度的距离*/
width: 50px;
height: 50px;
background-color: pink;
}
.son2{
width: 50px;
height: 50px;
background-color: green;
}
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
1.3.1 子绝父相定位
绝对定位使得子元素相对于祖先元素移动,那么究竟是那个祖先元素,是父代,还是更高的祖先代?因此,绝对定位需要一个“参考物”来明确祖先元素究竟是哪一代元素,这个参考物就是
相对定位position:relative
绝对定位将层级最近的,带有相对定位的祖先元素作为位移参考系
如果在其祖先元素里没有找到相对定位,那么子元素默认以视窗为参考系移动,如下所示