微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试使用display:flex,但是一些内联块永远不应该缩小.我不知道如何做到这一点.

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

.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的宽度不是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如下:

.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的每个子节点都变成了一个flex项:flex-grow:1; flex-shrink:1; flex-basis:0%; (See here for more info).

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

原文地址:https://www.jb51.cc/css/215681.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。