如何避免使用CSS max-width进行非必要的换行?

yvfmudvl  于 2023-03-24  发布在  其他
关注(0)|答案(1)|浏览(189)

天真地,我以为max-width: max-content;会根据需要来避免换行,但根据这个例子,情况似乎并非如此。在CSS中是否有任何方法可以将容器元素设置为仅根据需要的宽度,以避免文本换行达到100%宽度,但仍然允许文本在100%宽度时换行一次?换句话说,使其宽度为100%,除非max-contentwithout wrapping更窄,在这种情况下,使其成为max-content。我认为运行此代码段将说明我想要的-即使有足够的水平空间使容器更宽,文本也会换行。
换句话说,看起来max-content真的不是没有自动换行的内容的最大宽度--它是有自动换行的一些较小的宽度,虽然我不明白是什么。这个例子甚至 Package 了我,虽然我认为它不应该这样做。

.container {
    border: solid;
    max-width: max-content;
    display: flex;
}

.left {
    width: 75%;
}

.right { 
   border-left:  solid;
   width: 25%;
}
<div class="container">
  <div class="left">Text that I don't want to wrap unless needed when the outer container is at width 100%</div>
  <div class="right">lorem ipsum</div>
</div>
4c8rllxm

4c8rllxm1#

如果我理解正确的话,你可以用display: inline-flex来完成这个任务,如下所示:

.container{
  display: inline-flex;
  margin-bottom: 20px;
  border: 1px solid red;
}

div{
  border: 1px solid black;
}

.left{
  width: 75%;
}

.right{
  width: 25%;
}
<div class="container">
  <div class="left">Some short content</div>
  <div class="right">lorem ipsum</div>
</div>

<div class="container">
  <div class="left">Some really really long content that should wrap this text onto a second lineSome really really long content that should wrap this text onto a second lineSome really really long content that should wrap this text onto a second lineSome really really long content that should wrap this text onto a second lineSome really really long content that should wrap this text onto a second line</div>
  <div class="right">lorem ipsum</div>
</div>

Quick overview of inline vs block

相关问题