Reputation: 63709
I'm trying to use display: flex
, but some inline-block
s should never be shrunk. I'm not sure how to accomplish that.
Here's a repro of my situation:
.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>
The problem is that .marker
is not of specified width: 2em
, but instead is rather narrow.
I've read through 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 but couldn't find a solution there either. Lastly, I've also carefully reviewed the "duplicate" suggestions Stack Overflow gave me when I wrote this question, but no solution there either.
How can you specify a flex item to never shrink beyond a certain minimum width?
Upvotes: 54
Views: 116545
Reputation: 3192
Be sure to have the wrap code on your display flex:
display:flex;
flex-wrap:wrap;
Otherwise the min-width:xxx woun't have effect.
Upvotes: 1
Reputation: 14102
You can use flex-basis
and the flex-shrink
properties.
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.
Change your .marker
as follows:
.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>
Alternatively you could continue using width: 2em
and use just this flex-shorthand:
.marker
{
flex: 0 0 auto;
}
The problems you are experiencing are caused by the default values of the flex
property. Each child of a flex-container is becoming a flex item with: flex-grow:1; flex-shrink: 1; flex-basis: 0%;
(See here for more info).
This properties allows your flex item to shrink, which is not wanted in your implementation.
Upvotes: 47