深入解析position的五个值及z-index

在css的position中有5个值,分别是static(默认),relative,absolute,fixed和sticky。其中z-index的属性与position中的值密切相关。

static

static是position中的默认值,元素出文档流中正常排列,设置上下左右的值是无效的。

1
2
3
4
5
6
7
8
9
10
11
12
13
     .div1{
background-color: pink;
width:200px;
height:200px;
}
.div2{
position: static;
top:100px;
left:100px;
width: 100px;
height: 100px;
background-color: gray;
}

图1

fixed

从字面上就知道它是用于‘固定’的啦,可是是相对于谁固定呢?

fixed是相对于浏览器页面固定的,如果设置放在右下角,就像一个牛皮癣小广告黏在了页面上了。fixed是脱离文档流的。

1
2
3
4
5
6
7
8
9
10
11
12
body{
background:green;
height:1800px;
}
.div2{
position: fixed;
right:0px;
bottom:0px;
width: 100px;
height: 100px;
background-color: gray;
}

image-20201006225202484

relative

即相对定位,相对于元素本身的位置进行定位的,不脱离文档流。也就是说不管移到哪去了,原来在页面中占据的位置都在那。属于落叶归根型~

也可以用在父元素上,让absolute的子元素有个对照。

1
2
3
4
5
6
7
     .div2{
position: relative;
top:100px;
width: 100px;
height: 100px;
background-color: gray;
}

image-20201006232206364

设置的是top,却向下移动了,可以理解为:移动后是移动前的负的距离,需要自己想象一下

absolute

绝对定位相对于最近的已经定位的元素,不包括static默认属性,其他4个属性都可。都没有设置的话,就是相对于html根元素进行定位。absolute是脱离文档流的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 		.div1{
background-color: pink;
width:200px;
height:200px;
}
.div2{
position:start;
width: 100px;
height: 100px;
background-color: gray;
}
p{
position: absolute;
right:10px;
}
html:
<div class="div1">
<div class="div2">
<p>???</p></div>
</div>

image-20201006233135172

这是相对于根元素的定位。

z-index

首先先明确,z-index设置的是定位元素的显示顺序,只对于absolute,fixed和relative有效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
		.div1{

background-color: pink;
width:200px;
height:200px;
}
.div2{
position:absolute;
width: 100px;
height: 100px;
background-color: gray;
z-index:10;
}
.div3{
position:absolute;
width: 100px;
height: 100px;
left:50px;
top:50px;
background-color: black;
}
html <div class="div1">
<div class="div2"></div>
<div class="div3"></div>
</div>

image-20201006235326939

由于在html中的加载的顺序问题,灰色块被覆盖了,设置灰色块的z-index就可以解决这个问题了。

还有一点就是,如果有两个父元素,各自都包含了子元素,那么想让其中被覆盖的子元素上来的话,可以直接设置被覆盖的子元素的z-index,或者设置被覆盖的子元素的父元素的z-index,一起都带上来。

sticky

字面意思:黏,与fixed固定不同的是,sticky元素中的内容是可以换成另一个内容的,可以理解成黏住的东西是可以撕下来的嘛,固定了的就没那么好摘了。

sticky主要用于对scroll事件的监听,当某个元素与父元素的距离达到了sticky的要求时,这时sticky的效果就相当与fixed。

当滚动起来的时候,设置的top会变成与浏览器的距离。

脱离文档流的问题

子元素设置为fixed和absolute脱离文档流,会造成父元素高度的坍塌,具体表现就是,父元素不能包裹住子元素了。

解决的办法:参考清除浮动一文。

虽然fixed和absolute会形成块级格式化上下文BFC,但是它并不能解决父元素高度坍塌的问题,是可以防止垂直方法margin重叠

查看评论