【发布时间】:2018-03-15 08:32:39
【问题描述】:
我希望我的父 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>
【问题讨论】:
标签: javascript html css absolute