自动调整容器< DIV>高度以容纳绝对定位的孩子< DIV> [英] auto adjust container <DIV> height to accomodate absolutely positioned child <DIV>s

查看:177
本文介绍了自动调整容器< DIV>高度以容纳绝对定位的孩子< DIV>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

is there a way to auto adjust container DIV height to accomodate absolutely positioned child DIVs? i'd like to get something like


+-----------------------+
| 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>

但容器div保持零高度。我理解,这可能是预期的行为,因为元素是流出去的流当定位绝对,但有一个解决方法吗? (除了预先计算生成的高度并手动设置)

but the "container" div stays zero height. I understand, that this might be the expected behaviour, as elements are 'taken out' of the flow when positioned absolutely, but is there a workaround for this? (except for precalculating the resulting height and setting it manually)

推荐答案

如果使用position:relative而不是位置absolute将保留在元素所在的页面结构中,此空间将是您移动的元素的高度。

If you use position:relative instead of position absolute an empty space will stay in the page structure where the element should be, and this space will be the height of the element you've moved.

因此,您可以将chld1和chld2让他们并排,添加top&底部填充以推动块3向下并使用相对位置将它们分开并移动到任何高度。

So you could float chld1 and chld2 to get them side by side, add top & bottom padding to push chld 3 down and use position relative to split them apart and move to any height. Then use clear both on chld3.

#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;
}

<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>

这篇关于自动调整容器&lt; DIV&gt;高度以容纳绝对定位的孩子&lt; DIV&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆