自动调整容器<DIV>高度以容纳绝对定位的孩子<DIV> s

Dmi*_*mov 29 html css layout

有没有办法自动调整容器DIV高度,以适应绝对定位的儿童DIV?我想得到类似的东西

+-----------------------+
| container             |
|  +------+   +------+  |
|  | chld |   | chld |  |
|  |   1  |   |   2  |  |
|  |      |   |      |  |
|  +------+   +------+  |
|       +------+        |
|       | chld |        |
|       |   3  |        |
|       |      |        |
|       +------+        |
+-----------------------+

我尝试类似的东西:

<div class="container" style="position: relative; border: solid thin">
    <div class="chld" style="width: 20px; 
                             height: 20px; 
                             position: absolute; left: 5px; top: 5px;
                             border: dashed thin;"><div>
    <div class="chld" style="width: 20px; 
                             height: 20px; 
                             position: absolute; left: 30px; top: 5px;
                             border: dashed thin;"><div>
    <div class="chld" style="width: 20px; 
                             height: 20px; 
                             position: absolute; left: 15px; top: 30px;
                             border: dashed thin;"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

但"容器"div保持零高度.我理解,这可能是预期的行为,因为元素在绝对定位时被"取出",但是有解决方法吗?(预先计算得到的高度并手动设置除外)

小智 10

溢出:汽车

这是新的clearfix方法,FYI.但是,它并不总是将容器扩展到最高绝对定位的孩子的高度.


whe*_*hys 9

如果使用position:relative而不是position绝对值,则空白空间将保留在元素应该位于的页面结构中,并且此空间将是您移动的元素的高度.

所以你可以浮动chld1和chld2来并排放置它们,添加顶部和底部填充以向下推动chld 3并使用相对位置将它们分开并移动到任何高度.然后在chld3上使用clear清除.

就像是

#exp_outer {
  width: 400px;
  border: 1px solid black;
}
#chld1 {
  float: left;
  margin: 30px 0 20px;
  left: 50px
}
#chld2 {
  float: right;
  margin: 30px 0 20px;
  right: 50px;
}
#chld3 {
  left: 150px;
  clear: both;
}
.box {
  position: relative;
  width: 80px;
  height: 80px;
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<div id="exp_outer">
  <div id="chld1" class="box">Child1</div>
  <div id="chld2" class="box">Child2</div>
  <div id="chld3" class="box">Child3</div>
</div>
Run Code Online (Sandbox Code Playgroud)