CSS 绝对定位的容器大小自动适应内部相对定位的 div

CSS absolute positioned container size autofit to relative positioned divs inside

一共有三个div:一个容器,有绝对位置,上,左坐标,里面有两个div,有相对位置,上,左坐标。

我想将容器的大小动态扩展到内部定位的 div 元素(所以我不喜欢将 width/height 添加到容器元素)。

我的代码是:

https://jsfiddle.net/ruzds7bk/

css:

.container {
  position: absolute;
  border: 1px solid red;
}

.box {
  position: relative;

  width: 50px;
  height: 70px;
  background: #c00;
}

html:

<!-- I'd like that the container's size would be fitted to its elements. -->
<div class="container" style="top: 80px; left: 20px;">
  <div class="box" style="top: 50px; left: 75px;">absolute</div>
  <div class="box" style="top: 100px; left: 130px;">absolute</div>
</div>

<!-- Something like that, but without adding container's width and height. -->
<div class="container" style="top: 470px; left: 20px; width: 200px; height: 350px;">
  <div class="box" style="top: 100px; left: 75px;">absolute</div>
  <div class="box" style="top: 200px; left: 130px;">absolute</div>
</div>

使用 margin-topmargin-left 代替 topleft 作为内部 .box 元素

.container {
  position: absolute;
  border: 1px solid red;
  height: auto;
}

.box {
  position: relative;
  width: 50px;
  height: 70px;
  background: #c00;
}
<div class="container" style="top: 80px; left: 20px;">
  <div class="box" style="margin-top: 50px; margin-left: 75px;">absolute</div>
  <div class="box" style="margin-top: 100px; margin-left: 130px;">absolute</div>
</div>