<!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>
</head>
<body>
<div class="box">
<div class="b2">
<div style="overflow: auto;position: relative;">
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<!-- 这是绝对布局,我怎么样才可以让这个高度等于滚动条内容全部高度 -->
<div style="position: absolute;width: 100%; height: 100%; top: 0; background-color:aqua;opacity: 0.5;"></div>
</div>
</div>
</div>
<style>
.box {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
}
.b2 {
width: 100%;
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
</style>
</body>
</html>
代码在上面,我怎么样才能让子元素absolute根据父元素滚动内容的高度设置高度
解决方案:
参考评论解决方案(上述代码只需改动这个就行了):
<div style="overflow: auto;">
<div style="position: relative;">
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="width: 100%;height: 300px;background-color: black; margin-bottom: 20px;"></div>
<div style="position: absolute;width: 100%; height: 100%; top: 0; background-color:aqua;opacity: 0.5;"></div>
</div>
</div>
单独给内容区域在包裹一个
div
,然后给这个div
设置position:relative
。或者把
overflow:auto
属性移动到.box
类上。一个简单的例子:
知识点就一个:
确定位置的同时也可以获取这个祖先元素的宽/高等属性