前言
css中定位position常用属性,static、relative、absolute、fixed、stikcy
(配合 top,bottom,left,right z-index 使用)
z-index——层叠顺序,数字大,越靠前显示
总结——特点
- static(静态)——默认样式,文档正常布局
- relative(相对定位)——相对元素正常布局位置偏移
- absolute(绝对定位)——文档脱离文档,相对最近的父级设置了非static布局的元素定位
- 父级没设置非static定位相对html元素定位
- fixed(绝对定位)——脱离文档,相对视口定位
- transform:none\filter:none\perspective:none(影响fixed的定位,属性值非none)
- sticky(粘性定位)——根据滚动在relative跟fixed之间切换
失效情况- 父级设置overflow:hidden 失效
<div class="father">
<div class="son">
测试
</div>
</div>
relative(相对定位)
.son{
width: 100px;
height: 100px;
background-color: lightskyblue;
position: relative;
top: 50px;
}
absolute(绝对定位)
.father{
width: 300px;
height: 500px;
background-color: tan;
position:relative; // 最常使用
}
.son{
width: 100px;
height: 100px;
background-color: lightskyblue;
position: absolute;
top: 50px;
}
fixed(绝对定位)
.father{
width: 300px;
height: 500px;
transform: scale(1);// 绝对定位失效,其他transform属性也会导致,可自行调试
perspective: 12px; // 绝对定位失效
filter: blur(1px); // 绝对定位失效
}
.son{
width: 100px;
height: 100px;
background-color: lightskyblue;
position: fixed;
top: 50px;
right: 50px;
}
sticky(粘性定位)
.father{
width: 300px;
height: 700px;
background-color: tan;
overflow: hidden; // 会导致粘性效果失效
}
.son{
width: 100px;
height: 100px;
background-color: lightskyblue;
position: sticky;
top: 0px; // 父级元素靠近顶部0像素,产生吸顶效果
}