问题的最小再现:
.fixed{
display: inline-block;
max-width: 5em;
margin: 0.5em;
padding: 0.5em;
background-color: rgb(220,220, 220);
}
.wrapper{
margin: 0.5em;
padding: 0.5em;
background-color: rgba(0,200, 0, 0.1);
width: fit-content;
}
p{
display: inline-block
}
body{
}
.text{
margin: 0.5em;
padding: 0.5em;
background-color: rgb(220,220, 220);
}
<div class="wrapper">
<div class="fixed">fixed but unknown</div>
<div class="fixed">fixed but unknown</div>
<div class="fixed">fixed but unknown</div>
<div class="text">
this long paragraph should not increase the size of the parent but as you can see, it doessdfsdfsfsdfsdfsdf sdf sdf
</div>
</div>
如果删除文本div,可以看到绿色包装的宽度是根据3个固定块计算的,这正是我想要的。
但是我想要一个文本,它的宽度不能超过父文本的宽度。
如果将内容添加到文本div,可以看到它会增长,并使绿色包装的大小也会增加
Imo有两个解决方案:
使用固定宽度,但这不适合我的需要,我希望大小取决于固定块。
从流中输出文本,使用宽度为100%的文本包装div,相对位置,文本div将具有绝对位置。它可以工作,但在这种情况下,我需要根据它的子级计算文本包装器的高度,这是不可能的,因为它已经超出了流程
非常感谢您的阅读和帮助,如果我还不清楚,请告诉我
最佳答案
一个想法是将width:min-content;
与min-width:100%
结合使用,但是您应该注意min-content
的支持(https://developer.mozilla.org/en-US/docs/Web/CSS/width#Browser_compatibility)
.fixed{
display: inline-block;
max-width: 5em;
margin: 0.5em;
padding: 0.5em;
background-color: rgb(220,220, 220);
}
.wrapper{
margin: 0.5em;
padding: 0.5em;
background-color: rgba(0,200, 0, 0.1);
display:inline-block;
}
p{
display: inline-block
}
body{
}
.text{
margin: 0.5em;
padding: 0.5em;
background-color: rgb(220,220, 220);
width:min-content;
min-width:calc(100% - 1em);
box-sizing:border-box;
}
<div class="wrapper">
<div class="fixed">fixed but unknown</div>
<div class="fixed">fixed but unknown</div>
<div class="fixed">fixed but unknown</div>
<div class="text">
this long paragraph should not increase the size of the parent but as you can see, it doessdfsdfsfsdfsdfsdf sdf sdf
</div>
</div>