【问题标题】:Increase element's parent height (relative position) based on child's height (absolute position)根据子元素的高度(绝对位置)增加元素的父元素高度(相对位置)
【发布时间】:2021-12-29 03:16:48
【问题描述】:

如何根据具有绝对位置的子元素高度增加具有相对位置的父元素的高度。

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

PS:我不想使用任何脚本

预期:

我得到了什么:

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

【问题讨论】:

  • 绝对元素不在文档流中,因此它们不会扩展父元素。你为什么在这里使用absolute?
  • 我将它用于应用程序内的拖放功能。在获取输出时,如果父 div 具有背景颜色、边框等,我会遇到问题...
  • @aerial301,尝试了上述示例中的所有选项。在我的情况下,这些选项都不起作用:(
  • 所以如果你想使用绝对位置的孩子,你需要设置一个固定的父母高度。没有绝对子级会扩展父级的情况,因为它超出了流程,如果设置绝对位置则需要单独考虑

标签: html css


【解决方案1】:

此 sn-p 仅使用 CSS 为您提供所需的外观。

它通过在最后一个子元素上设置一个绿色背景来实现这一点,并让第一个子元素上的伪元素覆盖整个元素上方的位,使其看起来好像是不在那里。

使用伪元素类似地侵入边框。

.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.) 我无法控制子元素来赋予动态背景颜色(绿色)。 :(
  • 子元素没有被赋予背景颜色,所以我有点不知道这个问题是什么。
【解决方案2】:

在父类中将height:100% 更改为height:100px 或任意数量

因为绝对位置没有任何高度,您应该为父级定义高度。

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

【讨论】:

  • 对不起,高度应该根据孩子的位置动态增加。这就是我被打动的地方:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
相关资源
最近更新 更多