Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS flexbox dynamic resizing : prefer max-width

Tags:

I have a row flexbox container that wraps.
On the items in it, I set:

  • flex: 1; so items grow to fill horizontaly the container
  • min-width: X; max-width: Y;' so items stay within an acceptable size.

Here is a simple codepen example.

The problem (as viewable in the example) is the behavior of the resize-wrap.

What happens:
Each item is as small as possible so the maximum number of them is put in the first line, they then grow just as much needed to fill the line. Therefore the item's max-width is almost never reached and the items are much closer to min-width.

What I'm looking for:
Each item is as big as possible so the minimum number of them is put in the first line, they then shrink just as much needed to add a new item and fill the line. Therefore the item's min-width is almost never reached and the items are much closer to max-width.

In other words:
I want the minimum possible number of items per line, not the maximum.

Is there a way to do that in CSS without JS ?

Thanks !

like image 388
Salomon BRYS Avatar asked Aug 26 '14 13:08

Salomon BRYS


People also ask

Does Flex basis override width?

flex-basis is limited by both max-width/max-height and min-width/min-height. When declared, flex-basis will override the width / height property set on a flex container.

How do I make my flex item not stretch width?

By default, the child elements of a flexbox container will stretch vertically to fill the height of the container. This can be prevented by using the align-self property on the child element that you do not want to stretch. This Pen is owned by dev on CodePen.

Should I use width or flex basis?

There is no difference between how flex-basis: will function on your element and how width: will function on your element. Width will even obey flex-shrink when using Flexbox.

How do you get flex to carry the whole width?

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100% , and enable wrap on the container. The item now consumes all available space.


1 Answers

I think what you're looking for is flex-basis, justify-content, and align-content.

#container {   background-color: green;   display: flex;   flex-flow: row wrap;   justify-content: space-around;   align-content: stretch; }  .item {   flex: 1;   flex-basis: 200px;   height: 100px;   min-width: 100px;   max-width:200px;   margin: auto;   border: solid black 2px;   background-color: red; } 

If you want the red boxes to fill the entire area, you can take the max width off the div.item.

like image 181
Pixel Rubble Avatar answered Sep 30 '22 12:09

Pixel Rubble