我希望我的父 div 扩展内容的高度,因为我的内容是动态的。但是,内容必须(我认为)绝对定位,以便它们可以垂直重叠。
我已经得出结论,我必须使用 JS 来找到容器中最后一个元素从顶部到底部的偏移量,然后将高度设置为其。
我目前正在做这样的事情:
var lastElement = document.getElementById('three');
var bounds = lastElement.getBoundingClientRect();
var bottomOffset = bounds.top + $("#three").height();
$("#container").height(bottomOffset);
然而,这在我的应用程序中很笨重,高度的应用不是即时的,导致网站运行缓慢。
有没有更好的办法?
var lastElement = document.getElementById('three');
var bounds = lastElement.getBoundingClientRect();
var bottomOffset = bounds.top + $("#three").height();
$("#container").height(bottomOffset);
body,
html {
height: 100% padding: 0;
margin: 0;
}
.absolute {
display: inline-block;
position: absolute;
background-color: blue;
width: 100px;
height: 100px;
}
#two {
top: 80px;
left: 120px
}
#three {
top: 160px;
left: 240px;
}
#container {
position: relative;
width: 100%;
;
background-color: yellow;
;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="absolute" id="one"></div>
<div class="absolute" id="two"></div>
<div class="absolute" id="three"></div>
</div>
最佳答案
您可以在没有任何 JS 的情况下完成您的结果,而是使用 CSS margin
框周围以获得相同的结果。
对于水平边距,您也可以使用百分比(根据 OP 的要求)。
对于垂直边距,这会产生意想不到的结果,因为百分比仍将引用 width of the container (under "Property Values") ,不是高度。
html,body {height:100%; padding:0; margin:0;}
.container {
background-color: yellow;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 2%;
background-color: blue;
}
.box.one {margin-top:0; margin-bottom:160px;}
.box.two {margin-top:80px; margin-bottom:80px;}
.box.three {margin-top:160px; margin-bottom:0;}
<div class="container">
<div class="box one"></div>
<div class="box two"></div>
<div class="box three"></div>
</div>
margin 百分比:https://jsfiddle.net/xzq64tsh/3/
关于javascript - 是否可以让父元素(相对)填充其绝对定位内容的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288753/