position有五个属性这,分别对应
| 属性 | 说明 |
|---|---|
| absolute | 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
| fixed | 生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
| relative | 生成相对定位的元素,相对于其正常位置进行定位。因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。 |
| static | 默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 |
| inherit | 规定应该从父元素继承 position 属性的值。 |
position: absolute
absolute是参照最近的已定位的父元素,如果没有就参照<html>,脱离DOM流,不占据空间。
.div1 {
margin: auto;
width: 800px;
height: 800px;
background: rgb(243, 243, 243);
}
.div2 {
position: relative;
margin: auto;
width: 500px;
height: 500px;
background: rgb(190, 190, 190);
}
.div1>.div2>span:nth-of-type(1) {
position: absolute;
top: 20%;/*上下定位*/
left: 30%;/*左右定位*/
}
span根据最近的父级position(也就是div2)的位置来绝对定位位置,效果如下:

image.png
position: fixed
参照于浏览器窗口,脱离DOM流,不占空间,悬浮广告或者点击置顶比较常见
.div1 {
margin: auto;
width: 800px;
height: 800px;
background: rgb(243, 243, 243);
}
.div2 {
position: relative;
margin: auto;
width: 500px;
height: 500px;
background: rgb(190, 190, 190);
}
.div1>.div2>span:nth-of-type(1) {
position: fixed;
top: 20%;
left: 15%;
}
span根据网页窗口的大小来绝对定位位置,和屏幕分辨率也有关系,效果如下:

image.png
position:relative
以自身为参照,存在于DOM流中,占据空间
.div1 {
margin: auto;
width: 800px;
height: 800px;
background: rgb(243, 243, 243);
}
.div2 {
position: relative;
margin: auto;
width: 500px;
height: 500px;
background: rgb(190, 190, 190);
}
.div1>.div2>span:nth-of-type(1) {
position: relative;
top: 20%;
left: 15%;
}
span根据容器位置来相对定位,也就是根据div2的位置来定位。

image.png
position: inherit;
继承父级position
.div1 {
margin: auto;
width: 800px;
height: 800px;
background: rgb(243, 243, 243);
}
.div2 {
position: fixed;
margin: auto;
width: 500px;
height: 500px;
background: rgb(190, 190, 190);
}
.div1>.div2>span:nth-of-type(1) {
position: inherit;
top: 20%;
left: 15%;
}
position: inherit;继承父级的position,图中继承了div2的fixed。

image.png