相对定位和绝对定位区别
2020-05-22 本文已影响0人
陌盍
HTML代码:
<div id="test1">111111111111111</div>
<div id="test2">222222222222</div>
<div id="test3">333333333333333</div>

CSS代码:
#test1 {
height: 50px;
background: red;
}
#test2 {
height: 50px;
background: blue;
}
#test3 {
height: 50px;
background: yellow;
}

初始布局效果:

1.相对定位:
position: relative;
相对于原来位置移动,元素设置此属性之后仍然处在文档流中,不影响其他元素的布局。
将第二个 div#test2 设为相对定位,元素相对于原来位置偏移:
#test2 {
height: 50px;
background: blue;
position: relative;
left: 20px;
top: 20px;
}

效果图如下:

2.绝对定位:
position: absolute;
元素会脱离文档流,如果设置偏移量,会影响其他元素的位置定位
- 在父元素没有设置相对定位或绝对定位的情况下,元素相对于根元素定位(即html元素)(是父元素没有)。
- 父元素设置了相对定位或绝对定位,元素会相对于离自己最近的设置了相对或绝对定位的父元素进行定位(或者说离自己最近的不是static的父元素进行定位,因为元素默认是static)。
将第二个 div#test2 设为绝对定位,元素在没有定义宽度的情况下,宽度由元素里面的内容决定:
(1)不设置偏移量:
#test2 {
height: 50px;
background: blue;
position: absolute;
}

效果图如下,元素脱离文档流:


(2)设置偏移量:
#test2 {
height: 50px;
background: blue;
position: absolute;
left: 20px;
top: 20px;
}

效果图如下,元素脱离文档流,且在父元素没有设置相对定位或绝对定位的情况下,元素相对于根元素定位(即html元素):


总结:
relative:定位是相对于自身位置定位(设置偏移量的时候,会相对于自身所在的位置偏移)。设置了relative的元素仍然处在文档流中,元素的宽高不变,设置偏移量也不会影响其他元素的位置。最外层容器设置为relative定位,在没有设置宽度的情况下,宽度是整个浏览器的宽度。
absolute:定位是相对于离元素最近的设置了绝对或相对定位的父元素决定的,如果没有父元素设置绝对或相对定位,则元素相对于根元素即html元素定位。设置了absolute的元素脱了了文档流,元素在没有设置宽度的情况下,宽度由元素里面的内容决定。脱离后原来的位置相当于是空的,下面的元素会来占据位置。