我有一个带有两个孩子的固定位置的容器元素。两个孩子都包含文本。我希望其中一个子级可以动态设置包含其内容的容器的宽度。我希望其他孩子的文本根据该宽度自动换行。
例如:
.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
具有相同的宽度,并在其中包裹文本,例如:
我想到的解决方案是:
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 answer或specification中了解有关最小含量和最大含量的更多信息。
[
max-content
inline size:最窄 inline size,如果不使用盒子内所有软包装机会],则可能需要同时装入其内容] >>。- ,这可以通过选择较大的inline size来避免。大致来说,如果提取了包装盒中的所有软包装机会。,其内容将适合其内联大小。
[
inline size一个盒子可能不会导致in-dimension维度溢出min-content
inline size:最窄