CSS postion (定位)
postion属性指定了元素的定位类型
- static:静态定位
- relative:相对定位
- absolute:绝对定位
- fixed:固定定位
- sticky:粘性定位
CSS中的定位
定位与布局,俩这傻傻分不清
定位是针对整个页面来讲的,俩栏布局、三栏布局,是针对页面来说
而定位是针对某个元素来讲的,把这个元素定位到什么位置
static
所谓静态定位,就是我们的标准流。
在标准流里面,块级元素独占一行,行内元素共享一行。静态定位是HTML元素的默认值,静态定位元素不会受top、bottom、left、right的影响。
relative
相对定位,就是相对原来的位置进行定位,想多定位的最大特点就是不脱离标准流,相对自己进行一定的偏移
.one{
background-color: red;
position: relative;
left: 30px;
top:20px
}
.two{
background-color: aqua;
}
absolute
绝对定位,就是相对离自己最近,并且定了位的元素进行偏移,使用决定定位后的盒子会脱离标准流
.one{
background-color: red;
position: absolute;
left: 30px;
top:20px;
}
.two{
background-color: aqua;
}
绝对定位后的盒子,display会变成block
span{
position: absolute;
width: 300px;
height: 300px;
background-color:black;
}
默认情况下,决定定位的参考点
top:定位参考点是页面左上角,而不是浏览器的左上角
bottom:对应的是浏览器首屏窗口尺寸,对应大的页面左下角
子绝父相
.one {
width: 500px;
height: 500px;
border: 10px solid red;
padding: 20px;
position: relative;
.two{
position: absolute;
width: 200px;
height: 200px;
background-color: aqua;
padding: 20px;
}
.three{
position: absolute;
width: 100px;
height: 100px;
background-color: black;
}
}
这个其中two left未设置
设置left:0
所以,在子绝父相中,绝对定位相对位置是border左上内角
fixed
固定定位可以看作一种特殊的绝对定位
固定定位相对与浏览器窗口进行定位
无论页面如何滚动,该元素的位置都不会变化
案例:网站中左右俩侧中的广告
sticky
在CSS3中,新增一种定位方式:sticky
推荐一个网站,看看浏览器是否支持该属性
https://caniuse.com/
需要注意点
- 父元素的高度不能够低于sticky元的高度
- 设置阈值:top、bottom、left、right,同时设置时top优先级高于bottom,left高于right