【问题标题】:Css prevent child from expanding parent [duplicate]Css防止孩子扩大父母[重复]
【发布时间】:2021-10-29 23:32:22
【问题描述】:

我有一个宽度未知的容器和两个孩子。

我希望第一个孩子确定容器的宽度。

我想让第二个孩子包裹在容器内。

我怎样才能做到这一点,例如弹性盒子?

<div class="container">
  <div class="first">this determines the container width</div>
  <div class="second"> if this is too long, it wraps around</div>
</div>

【问题讨论】:

    标签: css flexbox grid


    【解决方案1】:

    首先您必须将 display: inline-block 添加到您的容器中,因为默认情况下 div 有 display: block 占用 100% 的宽度

    next 将.container 的宽度设置为max-content,因此它只需要容纳整个内容所需的空间,而.first 默认具有display: block,此元素将为.container 设置宽度

    最后在你的.second 元素上设置max-width: fit-content,这样它就会“适合”在容器中。

    .container {
        display: inline-block;
        background-color: red;
        width: max-content;
    }
    .second {
        max-width: fit-content;
    }
    <div class="container">
        <div class="first">this determines the container width</div>
        <div class="second">asd asd if this is too long, it wraps around asd asd</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2016-01-09
      • 2019-07-26
      • 2019-04-13
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多