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