CSS 防止在 flexbox 子元素中换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18340154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:02:09  来源:igfitidea点击:

prevent wrapping lines in flexbox child element

cssflexbox

提问by jessh

How do I prevent line wrapping of a flexbox element? Is it even possible?

如何防止 flexbox 元素换行?甚至有可能吗?

I'm attempting to create a two column grid with flexbox with the following markup:

我正在尝试使用带有以下标记的 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>

The .no-wrapelement should only be as wide as it 'needs to be' such that all of the text inside does not wrap to a second line. The .can-wrapelement will take up the remaining space, and wrap if need be.

.no-wrap元素的宽度应仅与其“需要”一样宽,这样里面的所有文本都不会换行到第二行。该.can-wrap元素将占用剩余空间,并在需要时换行。

I'm using this CSS (with prefrix free):

我正在使用这个 CSS(带有 prefrix 免费):

.flex-container{
  display:flex;
}

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

I thought the flex-basis:initialwould prevent the element from wrapping lines - https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis

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

Here's a codepen: http://codepen.io/jshawl/pen/bknAc

这是一个代码笔:http://codepen.io/jshawl/pen/bknAc

I know I can fix the width of the .no-wrapelement, but how can I make it be as wide enough to prevent line wrapping?

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

The float equivalent for the .no-wrapelement would be:

.no-wrap元素的等效浮点数将是:

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

回答by cimmanon

The property you are looking for is flex-shrink, not flex-basis.

您正在寻找的属性是flex-shrink,而不是flex-basis

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

Note however, that IE10 is not listed as supporting this property (as it did not exist in the specification at the time they added the Flexbox implementation). You can use the flexproperty instead.

但是请注意,IE10 并未列为支持此属性(因为在他们添加 Flexbox 实现时,规范中不存在它)。您可以改用flex属性。

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