定位之子绝父相
首先介绍position的四种值
- relative
- 相对定位
- 不脱离标准流
- 相对于自身调整
- absolute
- 绝对定位
- 脱离标准流
- 相对于最近的定位包裹元素调整
- fixed
- 固定
- 脱离标准流
- 相对于浏览器视口
- sticky
- 粘性定位
- 到达一定条件脱离标准流
- 相对于最近的滚动包裹元素
子绝父相的原理
利用绝对定位的特性
- 案例一
<style>
.box {
height: 400px;
width: 800px;
background-color: red;
}
.item {
height: 100px;
width: 300px;
background-color: green;
position: absolute;
left: 0;
right: 0;
}
</style>
<body>
<div class="box">
<div class="item">123</div>
</div>
</body>
item最近的父元素是box,但是他不是一个定位元素,所以最终定位相对于视口
- 案例二
<style>
.box {
height: 400px;
width: 800px;
background-color: red;
position: relative;
/* 这里无论哪个值会生效 */
}
.item {
height: 100px;
width: 300px;
background-color: green;
position: absolute;
left: 0;
right: 0;
}
</style>
<body>
<div class="box">
<div class="item">123</div>
</div>
</body>
当box元素设置为定位元素,无论是relative还是fixed、absolute。此时item相对的是box元素