是否可以使父元素(相对)填充其绝对定位内容的高度



我希望我的父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>

在 JSFiddle 上查看

您可以在

没有任何 JS 的情况下完成结果,但可以在框周围使用 CSS margin来获得相同的结果。

对于水平边距,您还可以使用百分比(根据 OP 的要求(。
对于垂直边距,这将产生意外的结果,因为百分比仍将引用容器的宽度(在"属性值"下(,而不是高度

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>
像素边距:https://jsfiddle.net/xzq64tsh/
利润率百分比:https://jsfiddle.net/xzq64tsh/3/

也许去掉getBoundingClientRect()函数,改用jQuery可能会加快速度并简化它。

var lastElement = $('#three');
var bottomOffset = lastElement.offset().top + lastElement.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>

最新更新