css - 滚动元素内的absolute
css - 滚动元素内的absolute
现象
scroll 内元素 absolute 定位异常
<!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>滚动元素内的absolute</title>
</head>
<style>
.box{
--size:200px;
width: var(--size);
height: var(--size);
overflow-y: auto;
border: 1px solid #00aaee;
}
.scroll-box{
width: 100%;
height: 500px;
}
.absolute{
position: absolute;
--size:50px;
bottom: 0;
right: 0;
width: var(--size);
height: var(--size);
background-color: yellow ;
}
</style>
<body>
<div class="box">
<div class="scroll-box">
<div class="absolute"></div>
</div>
</div>
</body>
</html>

absolute
元素是再 html
外的 是相对于window的
期望效果
无论scroll-box
如何滚动,absolute
始终向对于 box
定位
absolute 描述
absolute生成绝对定位的元素,相对于 static
定位以外的第一个父元素
进行定位。
解决
.box relative 未解决
位置相对于box
但会随scroll-box
移动

结论:position 无法脱离dom层级
dom 结构
改变dom层级
<style>
.box{
position: relative;
--size:200px;
width: var(--size);
height: var(--size);
border: 1px solid #00aaee;
}
.main{
width: 100%;
height: 100%;
overflow-y: auto;
}
.scroll-box{
width: 100%;
height: 500px;
}
.absolute{
position: absolute;
--size:50px;
bottom: 0;
right: 0;
width: var(--size);
height: var(--size);
background-color: yellow ;
}
</style>
<body>
<div class="box">
<div class="main">
<div class="absolute"></div>
<div class="scroll-box"></div>
</div>
</div>
</body>

Lee2