禁用元素的增长能力

时间:2018-12-11 09:53:07

标签: html css

问题的最小再现:

.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%(相对位置)的text-wrapper div从流中输出文本,并且text div将具有绝对位置。它可以工作,但是在这种情况下,我需要根据文本包装器的子高度来计算它的高度,这是不可能的,因为它超出了流量

非常感谢您的阅读和帮助,请告诉我是否不清楚

2 个答案:

答案 0 :(得分:1)

一个想法是将width:min-content;min-width:100%结合使用,但是您应该注意min-contenthttps://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>

答案 1 :(得分:0)

如果我能正确理解您的意思,那么您希望将下部行的宽度与上部3列的宽度相匹配。

您可以通过考虑边距和填充来计算3列的宽度(每列5em)。我用它作为宽度,你也可以用它作为最大宽度

.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);
  width: 19.5em;
}
<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>