避免在Flexbox子元素中换行

70

我该如何防止 flexbox 元素换行?这是否可能?

我试图使用以下标记创建具有两列的 flexbox 网格:

<div class="flex-container">
   <div class="no-wrap">this should not wrap</div>
   <div class="can-wrap">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam debitis consequuntur incidunt neque vel in blanditiis id optio distinctio culpa rem voluptatibus quas architecto ratione assumenda omnis laboriosam? Earum esse.</div>
</div>

.no-wrap元素应该只有它需要的宽度,以便所有内部文本不会换行到第二行。 .can-wrap元素将占据剩余空间,并在需要时换行。

我正在使用以下CSS(无前缀):

.flex-container{
  display:flex;
}

.no-wrap{
  flex-basis:initial;
}

我认为flex-basis:initial会防止元素换行 - https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis

这里是一个CodePen:http://codepen.io/jshawl/pen/bknAc

我知道我可以修复.no-wrap元素的宽度,但如何使它足够宽以防止换行?

.no-wrap元素的浮动等效物将是:

.no-wrap{
  display:block;
  float:left; /* be as wide as need be! */
}
2个回答

124

你要查找的属性是 flex-shrink,而不是 flex-basis

.no-wrap{
  flex-shrink: 0;
}

需要注意的是,IE10并未列出支持该属性(因为在他们添加Flexbox实现时该属性并不存在于规范中)。您可以使用flex属性来替代。

.no-wrap{
  flex: 0 0 auto; 
}

8
如果 flex-shrink 属性不能解决问题,可以尝试将 white-space 设置为 nowrap
.no-wrap {
  white-space: nowrap
}

你也可以使用 pre 来保留换行符(不像 nowrap)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接