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

时间:2019-11-14 10:52:39

标签: html css position expand

一共有三个div:一个具有绝对位置,顶部,左坐标的容器,另一个是位于内部且具有相对位置,顶部和左坐标的两个div。

我想将容器的大小动态扩展到内部的已定位div元素(因此,我不喜欢在容器元素中添加宽度/高度)。

我的代码是:

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>

1 个答案:

答案 0 :(得分:0)

对于内部margin-top元素,使用margin-lefttop代替left.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>