防止子级拉伸父容器[重复]

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

我有一个带有两个孩子的固定位置的容器元素。两个孩子都包含文本。我希望其中一个子级可以动态设置包含其内容的容器的宽度。我希望其他孩子的文本根据该宽度自动换行。

例如:

.container {
  position: fixed;
}

.wrap {
  background: red;
}

.stretch {
  background: green;
}
<div class="container">
  <div class="wrap">
    this text is very very long
  </div>
  <div class="stretch">
    shorter text
  <div>
</div>

在此示例中,我希望容器的宽度与较短的绿色.stretch div相匹配。我希望红色.wrap div具有相同的宽度,并在其中包裹文本,例如:

r

html css word-wrap
1个回答
2
投票

我想到的解决方案是:

  • div需要伸展其宽度取决于其内容-> max-content
  • 父母的宽度需要尽可能缩小取决于其内容-> min-content

具有不同行为的解决方案代码:

.container {
  width: min-content;
  
  border: 2px solid blue;
  margin: 5px;
}

.wrap {
  background: red;
  width: auto; /* default btw */
}

.stretch {
  background: green;
  width: max-content;
}
<div class="container">
  <div class="wrap">
    this text is very very long
  </div>
  <div class="stretch">
    shorter text
  </div>
</div>

<div class="container">
  <div class="wrap">
    shorter
  </div>
  <div class="stretch">
    shorter text
  </div>
</div>

<div class="container">
  <span class="wrap">
    shorter
  </span>
  <div class="stretch">
    shorter text
  </div>
</div>

您可以从this answerspecification中了解有关最小含量和最大含量的更多信息。

  • [max-content inline size最窄 inline size,如果不使用盒子内所有软包装机会],则可能需要同时装入其内容] >>。

  • [min-content inline size最窄

    inline size一个盒子可能不会导致in-dimension维度溢出
  • ,这可以通过选择较大的inline size来避免。大致来说,如果提取了包装盒中的所有软包装机会。,其内容将适合其内联大小。
© www.soinside.com 2019 - 2024. All rights reserved.