我正在尝试使用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-basis
和
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;
- }
或者你可以继续使用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项缩小,这在您的实现中是不需要的.