让子级在绝对上下文中填充父级最大宽度

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

我有相当于这个简化示例的第二种情况(div 组)的东西,第一个只是为了表明它在绝对上下文之外工作,子级尽可能扩展,直到达到父级 max-width :

.abs {
  position: absolute;
  top: 50px;
}

.parent {
  /*
    This div is reused across the web with different dynamic content
    Its only constraint to the children should be a maximum width
  */
  max-width: 300px;
}

.child {
  /*+
    This is one of the multiple children the parent will have
    In this case it should should always try to grow as much as allowed by its parent
  */
  width: 100%;
  background-color: lightblue;
}
<div class='parent'>
  <div class='child'>
    Foo
  </div>
</div>

<div class='abs'>
  <div class='parent'>
    <div class='child'>
      Bar
    </div>
  </div>
</div>

考虑到绝对div对于我的特定需求是强制性的,有没有办法让子元素填充其父元素最大宽度?

html css absolute
1个回答
0
投票

这就是 W3C 的规定:

绝对定位的元素将收缩包裹以适合其内容,除非您指定其尺寸。您可以通过设置 left 和 right 属性或设置 width 属性来指定宽度。您可以通过设置 top 和 Bottom 属性,或者通过设置 height 属性来指定高度。

因此,您需要指定绝对元素的宽度。

.abs {
  position: absolute;
  top: 50px;
  width: 100%;
}

.parent {
  max-width: 300px;
}

.child {
  width: 100%;
  background-color: lightblue;
}
<div class='parent'>
  <div class='child'>
    Foo
  </div>
</div>

<div class='abs'>
  <div class='parent'>
    <div class='child'>
      Bar
    </div>
  </div>
</div>

我假设您正在使用某种框架来完成您的任务 - 指定宽度可以放置在组件样式表内,因此最终使用它的每个组件都可以提供首选宽度(以及其他样式)

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