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

前端之家收集整理的这篇文章主要介绍了css – 如何指定弹性项目具有一定的最小宽度?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用display:flex,但是一些内联块永远不应该缩小.我不知道如何做到这一点.

这是我的情况的一个重演:

  1. .marker {
  2. width: 2em;
  3. height: 2em;
  4. background-color: #cef;
  5. border: 1px solid gray;
  6. margin-right: 5px;
  7. }
  8.  
  9. label {
  10. display: flex;
  11. align-items: flex-start;
  12. }
  1. <div class="container" style="width: 200px; border: 1px solid #ccc; padding: 10px;">
  2. <p>The blue Boxes should be 2em wide!</p>
  3. <label>
  4. <span class="marker"></span>
  5. <span class="text">Some rather long text which is the whole reason for using flexBox.</span>
  6. </label>
  7. <label>
  8. <span class="marker"></span>
  9. <span class="text">Short text.</span>
  10. </label>
  11. </div>

问题是.marker的宽度不是2em,而是相当窄.

我已经阅读了css-tricks’ helpful Guide to Flexbox.唯一看似有用的属性是flex-shrink(我期待一些“永不缩小”的属性),但是没有办法将它用于我的目的.我已经撇去了the MDN flex pages,但也找不到解决办法.最后,我还仔细阅读了Stack Overflow在撰写此问题时给出的“重复”建议,但也没有解决方案.

如何指定弹性项目永远不会缩小到超过某个最小宽度?

解决方法

您可以使用 flex-basisflex-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如下:

  1. .marker {
  2. flex: 0 0 2em;
  3. height: 2em;
  4. background-color: #cef;
  5. border: 1px solid gray;
  6. }
  7.  
  8. label {
  9. display: flex;
  10. align-items: flex-start;
  11. }
  1. <div class="container" style="width: 200px; border: 1px solid #ccc; padding: 10px;">
  2. <p>The blue Box should be 2em wide!</p>
  3. <label>
  4. <span class="marker"></span>
  5. <span class="text">Some rather long text which is the whole reason for using flexBox.</span>
  6. </label>
  7. </div>

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

  1. .marker
  2. {
  3. flex: 0 0 auto;
  4. }

您遇到的问题是由flex属性的默认值引起的. flex-container的每个子节点都变成了一个flex项:flex-grow:1; flex-shrink:1; flex-basis:0%; (See here for more info).

属性允许您的flex项缩小,这在您的实现中是不需要的.

猜你在找的CSS相关文章