position:relative相对定位不脱离文档流
虽然position:relative相对定位不脱离文档流,但是可以用z-index属性,(
tips
:设置了position: relative,那么该元素看起来也会提升了文档流,但是不会真正脱离,还在它原来那个位置,只是看起来高度提升了,即看起来z-index被默认设置为0了),也可以通过top/right/bottom/left来指定位置。原因是因为相对定位本来还保留了它的空间。
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8" />
<meta name="author" content="http://www.51qianduan.com/" />
<title>position:relative相对定位不脱离文档流</title>
<style type="text/css">
#top {
width: 100px;
height: 100px;
background: #ccc;
position: relative;
left: 130px;
}
#bottom {
width: 100px;
height: 100px;
background: green;
}
</style>
</head>
<body>
<div id="top"></div>
<div id="bottom"></div>
</body>
</html>
可以看到,相对定位的原来位置依然被保存,后面的元素并不能顶上来。
子元素z-index逃不出父元素的z-index
如果在一个父元素上设置了position: absolute; z-index: 2; 。而在起子元素上设置了position: absolute; z-index: 999; 那么子元素也是逃不出父元素的z-index的,即子元素的z-index不会生效。
position: absolute; 如果不指定top,top的默认值位置是相对于正常文档流的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#one {
width: 300px;
height: 300px;
background-color: red;
}
#two {
width: 400px;
height: 400px;
background-color: green;
position: absolute;
/* top: 0; */
/* 默认值 */
top: auto;
}
#three {
width: 30px;
height: 30px;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
</body>
</html>
当你使用position: absolute;
时,元素的位置是相对于其最近的已定位祖先元素或者文档本身。如果你不指定top
、right
、bottom
或 left
中的任何一个值,元素将会保持在其在正常流中的位置
,因为它的偏移值将会是默认值 auto
。
如果你不设置top: 0;,或者设置top为其他值,浏览器将根据文档正常流中元素的默认位置来定位"two"元素。
在这个例子中,如果你省略 top: 0;
,“two” 元素将会以默认的偏移值(auto)相对于文档流中的位置定位。因为它之前没有明确定义的位置,可能会根据文档流中相邻元素的位置来定位。因此,通过设置 top: 0;
,你确保了它相对于文档的顶部对齐。
总结,top: 0;
的设置是为了确保 “two” 元素相对于其包含块(文档的 body)的顶部对齐,而不是为了脱离文档流。
position: absolute定位
position: absolute定位如果没有已定位的父元素,则相对于初始包含块进行定位,初始包含块是相对于视口(浏览器窗口)。
定位属性insert
CSS 属性 inset 为简写属性,对应于 top、right、bottom 和 left 属性。其与 margin 简写属性具有相同的多值语法。
伪元素定位相关
伪元素在结构上虽然和与设置伪元素的元素不是父子关系,但是在相对定位上,如果#test设置了相对定位,那么#test的伪元素会相对#test来进行定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#root {
padding: 30px;
}
#header {
width: 1000px;
height: 30px;
background-color: green;
}
#test {
/* position: relative; */
background-color: red;
width: 100px;
height: 100px;
}
#test::after {
content: '';
display: block;
width: 80px;
height: 80px;
background-color: gray;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div id="root">
<div id="header">232</div>
<div id="test"></div>
</div>
</body>
</html>
- #test未设置position: relative
- #test设置了position: relative