防止孩子拉伸父容器

时间:2020-01-01 12:43:31

标签: html css word-wrap

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

例如:

.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

1 个答案:

答案 0 :(得分: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的盒子可能不会导致在线尺寸溢出,可以通过选择较大的inline size来避免。大致来说,如果使用了包装盒中的所有软包装机会,其内联大小将适合其内容。