1. 绝对定位元素的祖先元素没有使用非static
的属性进行定位时
此时,绝对定位元素相对与初始包含块ICB
进行定位
初始包含块ICB
是包含html
的块,相当于html
的父元素
1. html
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
border: 0;
}
html{
background-color: wheat;
width: 562px;
height: 500px;
position: static;
top: 100px;
left: 300px;
border: 1px solid black;
margin-top: 300px;
}
body{
background-color: yellowgreen;
border: 1px dashed red;
}
#wrapper{
background-color: darkgray;
}
.box {
display: inline-block;
background-color: red;
box-sizing: border-box;
color: white;
width: 100px;
height: 100px;
float: left;
opacity: 0.3;
margin: 22px;
}
#three{
position: absolute;
top: 102px;
}
div#test{
background-color: darkcyan;
}
</style>
</head>
<body>
<div id="wrapper">
<div class="box" id="one">one</div>
<div class="box" id="two">two</div>
<div class="box" id="three">three</div>
<div class="box" id="four">four</div>
</div>
<div id="test">test</div>
</body>
</html>
2.渲染效果:
2. 祖先元素使用非static
定位时
此时,绝对定位元素相对于其最近的使用非static
定位的祖先元素
下面代码时上面代码的改动处,便于对比查看:
#wrapper{
background-color: darkgray;
position: relative;
}
#three{
position: absolute;
top: 30px;
left: 30px;
}
使用绝对定位的元素three 颜色块
相对于其父元素#wrapper
定位
总结
static
定位:默认定位,此时top
,bottom
,left
,right
,z-index
无效
相对定位relative
:元素不脱离文档流,不改变页面布局,相对自身的top
等属性定位
绝对定位absolute
:脱离文档流,改变页面布局,相对于初始包含块ICB
或者使用非static
定位的祖先元素
固定定位fixed
:与绝对定位类似,脱离文档流,改变页面布局,相对于浏览器视口定位
粘性定位sticky
:相对定位与固定定位的组合,相对于自身或浏览器视口定位
初始包含块ICB
就是浏览器视口viewport
,该视口宽高可变,宽高随着浏览器的放大缩小而变化
绝对定位与固定定位都相对于视口定位的条件:使用这两个定位的元素没有使用非static
祖先元素,此时两种定位效果类似
续:html
继承视口高度
html{
height: 100%; // 视口有多高, 这个height就是多高
}
body{
height: 100%; // html有多高,这个height就是多高
}