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

标签 javascript html css absolute

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

View on JSFiddle

最佳答案

您可以在没有任何 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>
像素边距:https://jsfiddle.net/xzq64tsh/
margin 百分比:https://jsfiddle.net/xzq64tsh/3/

关于javascript - 是否可以让父元素(相对)填充其绝对定位内容的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288753/

相关文章:

html - 从一个类转移到另一个类的属性...

html - 设计隐藏的输入

html - 了解图像在不同浏览器中的位置

javascript - 为什么 Intl 和 Reflect 的默认字符串表示为 `[object Object]` ?

javascript - 指令范围始终为空

javascript - 为什么 dropzone 不提交文件?

javascript - HTML 标记中的下载属性不适用于 BLOB 文件

html - 如何使 Bootstrap 设计的 HTML 颜色边到边

jquery - 有没有更好的方法来使用 jQuery 切换

javascript - Hapi.js 文件上传 我如何获取文件以便我可以在其上使用 imageMagick 命令行工具