定位:更高级的布局手段,所有元素都可以使用定位
通过浮动,外边距等都不能实现位置效果的时候,就使用定位
属性:
position
取直:
static 默认值,没有设置定位
relative:相对定位
偏移时参考位置:元素本身的初始位置
特点:
1.不脱离标准文档流
2.初始位置继续占用
3.会覆盖标准文档流里面的文本内容
例:
div.first { width: 100px; height: 100px; background-color: pink; /* 设置相对定位 */ position: relative; /* 向右平移50px 向下平移50px */ /* 平移过后元素的左边离元素初始位置的左边距离为50px */ left: 50px; top: 50px; } <div class="wrap"> <div class="first"></div> </div>
absolute:绝对定位
偏移时参考位置:离他最近的"开启定位的祖先元素",如果没有祖先元素开启定位,参考变为body
特点:
1.margin:0 auto,水平居中和浮动没有效果
2.设置绝对定位的元素脱离标准文档流
3.原来位置不会继续占用,后面标准文档流中的兄弟元素上移
4.会覆盖标准文档流里面的文本内容
一般作为绝对定位的参考是是将祖先元素设置为相对定位
例:
/* 绝对定位 */ .ab { width: 300px; height: 300px; margin: 100px auto; background-color: lightgreen; /* position: absolute; */ /* position: relative; */ } .ab>.son { width: 100px; height: 100px; background-color: red; /* 设置绝对定位 */ position: absolute; /* 设置偏移 */ left: 200px; } <div class="fa"> <div class="ab"> <div class="son"></div> 太嗣活九,轻尺家派。 </div> </div> <div> 这里.son会将.ab覆盖
fixed:固定定位,就是特殊的绝对定位
偏移时参考位置:浏览器视口
特点:
1.设置绝对定位的元素脱离标准文档流
3.原来位置不会继续占用,后面标准文档流中的兄弟元素上移
例:
.fi { width: 100px; height: 100px; background-color: lightcoral; /* 设置固定定位 */ position: fixed; right: 0; top: 50px; } <div class="fi"></div>
粘滞定位
sticky
参考位置:离父元素的距离,如果离父元素的距离与设置一致,就固定不动
特点:不脱离标准文档流,原先位置继续占有
例:
.fa { width: 300px; height: 100px; background-color: pink; /* 设置滚动条 */ /* overflow-y: scroll; */ overflow: auto; } .item { height: 30px; background-color: blue; /* 设置粘滞定位 */ position: sticky; top: 40px; }