如何在相对父容器中包含绝对子容器

问题描述 投票:0回答:2

有没有办法让相对父高容器根据他的绝对孩子成长?

https://codepen.io/daniele-acquaviva/pen/JzpzxG

.relative-parent {
  background: red;
  position: relative;
  text-align: center;
}

.absolute-child {
  background: yellow;
  position: absolute;
  top: 0;
}
<div class="relative-parent">
  <p> Parent div content </p>
  <div class="absolute-child">
    <p> child </p>
    <p> child </p>
    <p> child </p>
    <p> child </p>
    <p> child </p>
    <p> child </p>
  </div>
</div>
html css frontend css-position absolute
2个回答
1
投票

如果您对孩子使用position: absolute;,则不会将其纳入父内容。

根据w3schools文件:https://www.w3schools.com/cssref/pr_class_position.asp

元件相对于其第一定位(非静态)祖先元件定位


编辑:这可以用javascript实现,请看这里https://codepen.io/tmacpolo/pen/ywvWbb

EDIT2:添加MutationObserver以在孩子的身高变化时调整父亲的身高https://codepen.io/tmacpolo/pen/ywvWbb


0
投票

这实际上是不可能的,因为绝对有效,因为它不受布局的影响。避免折叠的唯一方法是为其父元素赋予力高度。

© www.soinside.com 2019 - 2024. All rights reserved.