根据子元素的高度(绝对定位),增加元素父级的高度(相对定位)

6

如何增加具有相对位置的父元素的高度,该父元素基于具有绝对位置的子元素的高度。

在下面的示例中,.parent 元素的高度显示为 0px

注:我不想使用任何脚本

期望结果:

enter image description here

实际结果:

enter image description here

jsFiddle 示例

HTML 代码:

<div class="parent">
    <div class="child" style="top:20px;">Hello</div>
    <div class="child" style="top:40px;">Some content</div>
    <div class="child" style="top:60px;">Some more content</div>
</div>

CSS:

.parent{position:relative;background:green;height:100%;border:1px solid #000000;width:250px;}
.child{position:absolute;}

1
这个回答解决了您的问题吗?使绝对定位的DIV扩展父级DIV高度 - aerial
1
绝对定位的元素不在文档流中,因此它们不会扩展父元素。你为什么要在这里使用绝对定位呢? - Ania Kowalska
我正在应用程序中使用这个功能来实现拖放。但是在获取输出时,如果父级div有背景颜色、边框等,我遇到了问题... - Reddy
@aerial301,我尝试了上面的所有选项。但是在我的情况下,没有一个选项起作用 :( - Reddy
1
如果您想使用绝对定位的子元素,那么您需要设置固定的父元素高度。绝对定位的子元素不会扩展父元素,因为它们不在流程中,所以如果您设置了绝对定位,就需要单独考虑它们。 - Ania Kowalska
2个回答

2
这段代码只使用CSS就可以实现你想要的外观。
它通过在最后一个子元素上创建一个伪元素,设置绿色背景并向上延伸很长一段距离,然后在第一个子元素上创建一个伪元素来覆盖整个元素上方的部分,使其看起来好像不存在。
边框也是使用伪元素“hack”进去的。

enter image description here

.parent {
  position: relative;
  width: 250px;
}

.child,
.child::before,
.child::after {
  box-sizing: border-box;
}

.child {
  position: absolute;
}

.child:first-child::before {
  content: '';
  position: absolute;
  bottom: 1em;
  background-color: white;
  width: 250px;
  height: 100vh;
  z-index: -1;
  border-bottom: 1px solid #000000;
}

.child:last-child::before {
  content: '';
  position: absolute;
  bottom: 0;
  background-color: green;
  width: 250px;
  height: 100vh;
  border: 1px solid #000000;
  border-top-width: 0;
  z-index: -2;
}
<div class="parent">
  <div class="child" style="top:20px;">Hello</div>
  <div class="child" style="top:40px;">Some content</div>
  <div class="child" style="top:60px;">Some more content</div>
</div>

它不能设置父元素的高度,也不会这样做。而且有一个假设,即父元素上面的背景是白色的(当然它可以有任何内置颜色,但这并不完全通用 - 更像是一种练习)。

@A Haworth,感谢您的回答,但它并没有按预期工作。1)在父元素顶部获得额外的空间,您已经用白色背景颜色覆盖了它。2)我无法控制子元素以给出动态背景颜色(绿色)。:( - Reddy
子元素没有设置背景颜色,所以我有点不知所措,不确定问题出在哪里。 - A Haworth

1

height:100%更改为height:100px或您想要的高度,放在父类中。

因为绝对定位没有任何高度,所以您应该为父元素定义高度。

.parent{
    position:relative;
    background:green;
    height:100px;
    border:1px solid #000000;
    width:250px;
 }

抱歉,高度应该根据子元素的位置动态增加。这就是我卡住的地方 :( - Reddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接