如何指定弹性项目具有一定的最小宽度?

How to specify a flex item to be of certain minimum width?

我正在尝试使用 display: flex,但某些 inline-block 永远不应缩小。我不确定如何实现。

这是我的情况的重现:

.marker {
  width: 2em;
  height: 2em;
  background-color: #cef;
  border: 1px solid gray;
  margin-right: 5px;
}

label {
  display: flex;
  align-items: flex-start;
}
<div class="container" style="width: 200px; border: 1px solid #ccc; padding: 10px;">
  <p>The blue boxes should be 2em wide!</p>
  <label>
    <span class="marker"></span>
    <span class="text">Some rather long text which is the whole reason for using flexbox.</span>    
  </label> 
  <label>
    <span class="marker"></span>
    <span class="text">Short text.</span>    
  </label> 
</div>

问题是 .marker 不是指定的 width: 2em,而是相当窄。

我通读了 css-tricks' helpful Guide to Flexbox. The only property that seemed useful was flex-shrink (I was expecting something of a "never shrink" property), but found no way to use it for my purpose. I've skimmed the MDN flex pages 但也找不到解决方案。最后,我也仔细看了写这个问题时Stack Overflow给我的"duplicate"建议,但也没有解决方案。

如何指定弹性项目永远不会收缩超过特定的最小宽度?

您可以使用 flex-basis and the flex-shrink 个属性。

The CSS flex-basis property specifies the flex basis which is the initial main size of a flex item. The property determines the size of the content-box unless specified otherwise using box-sizing.

按如下方式更改您的.marker

.marker {
  flex: 0 0 2em;
  height: 2em;
  background-color: #cef;
  border: 1px solid gray;
}

label {
  display: flex;
  align-items: flex-start;
}
<div class="container" style="width: 200px; border: 1px solid #ccc; padding: 10px;">
  <p>The blue box should be 2em wide!</p>
  <label>
    <span class="marker"></span>
    <span class="text">Some rather long text which is the whole reason for using flexbox.</span>    
  </label>  
</div>

或者您可以继续使用 width: 2em 并只使用这个 flex-shorthand:

.marker
{
    flex: 0 0 auto;
}

您遇到的问题是由 flex 属性 的默认值引起的。 flex-container 中的每个 child 都将成为弹性项目:flex-grow:1; flex-shrink: 1; flex-basis: 0%; (See here for more info).

此属性允许您的 flex 项目收缩,这在您的实现中是不需要的。

请务必在您的显示器 flex 上设置换行代码:

display:flex;
flex-wrap:wrap; 

否则min-width:xxx不会生效