How to specify an element of flexibility of a certain minimum width?

I am trying to use display: flex , but some inline-block should never be shortened. I am not sure how to do this.

Here is an example 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 not specified width: 2em , but rather narrow.

I read the helpful css-tricks guide to Flexbox . The only property that seemed useful was flex-shrink (I was expecting something like the “never compress” property), but found no way to use it for my purpose. I shot the flexible MDN pages but could not find a solution. Finally, I also carefully considered the "duplicate" sentences that Qaru gave me when I wrote this question, but there was no solution.

How can you specify an element of flexibility to never shrink beyond a certain minimum width?

+6
source share
1 answer

You can use flex-basis and flex-shrink properties.

The flex property of flex is based on flexibility, which is the initial primary size of a flex item. The property determines the size of the content field, unless otherwise specified, using the size of the window.

Modify .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 can continue to use width: 2em and use only this flex shorthand:

 .marker { flex: 0 0 auto; } 

The problems you are experiencing are caused by the default flex property. Each child element of a flexible container becomes a flexible element: flex-grow:1; flex-shrink: 1; flex-basis: 0%; flex-grow:1; flex-shrink: 1; flex-basis: 0%; ( See here for more details ).

These properties allow the flex item to contract, which is not required in your implementation.

+4
source

Source: https://habr.com/ru/post/983854/


All Articles