I have a flex container with flex-wrap: wrap
and align-items: stretch
so that children gets stretched when the container is resized up until the next child fits.
The problem is usually the last line has less elements than previous lines and children get stretched too much (all the boxes should look the same in every situation). How can I prevent that other than creating a bunch of empty boxes at the end of the container?
body {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-align-items: stretch;
align-items: stretch;
}
.child {
height: 50px;
margin: 10px;
-webkit-flex: 1 1 50px;
flex: 1 1 50px;
background-color: red;
border: 1px solid black;
}
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
JSFiddle is here: http://jsfiddle.net/m_gol/B3wLG/2/
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.
In a multi-line flex row layout, the align-content controls how the flex items aligns vertical when they wrap, and since its default is stretch , this is expected behavior. Change it to align-content: center; and you'll see how their alignment change to vertical middle.
The only solution I've found to this so far is to programatically add some empty child elements to make up a complete row - it's fine to add more than the row so they overspill (as they're empty).
The dead easiest way is to remove the flex from the last item:
.flex-item:last-child{
flex-grow: 0;
}
Or give it a small fraction of growth, so it doesn't look too little either (especially if everything else has grown a little)
.flex-item:last-child{
flex-grow: 0.1;
}
If neither of these work, add an empty div as your last item, and give it a much larger growth - also hide any borders and backgrounds, and give it a zero height so it doesn't take up another line
.flex-item:last-child{
background: none;
border: none;
height: 0px;
flex-grow: 100;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With