I’m looking for a way to align multiple items next to each other, having them wrap once they fill up the line, and the last item take up the remaining width of the last line.
I have found multiple questions on a similar topic before, with solutions generally making the items use float: left
to align them on a line, and overflow: hidden
on the last element which makes it take up the remaining space automatically. Those solutions work fine in a single line, but they stop working once there are enough items before the last element, that they wrap into multiple lines. Then, the “last” element is still rendered in the first row (if there is enough space), making it no longer be the last element.
However, I want the last element to stay the last element at all times, to have it in the last row—whatever row that is—and automatically take up the remaining space there.
This is pretty simple with a wrapping flexbox, since you just need to put flex: 0 auto
on the former items to make them take up whatever space they need (without taking more), and flex: 1
on the last element to make it take up the remainder. However, I need to support Internet Explorer 9, so flexbox is unfortunately out of the question.
This is how the situation looks like. When running the snippet, you can use the “Toggle flex box” button to toggle flexbox mode which shows the way it should look like.
* { box-sizing: border-box; }
.container {
width: 300px;
background: snow;
padding: 5px;
overflow: auto;
}
.element {
float: left;
margin: 2px 5px 2px 0;
background: lavender;
}
.last {
overflow: hidden;
}
.last > input {
width: 100%;
}
/* Working solution with flex box */
.flex .container {
display: flex;
flex-wrap: wrap;
}
.flex .element {
flex: 0 auto;
}
.flex .last {
flex: 1;
}
<div class="container">
<div class="element">Foo</div>
<div class="element">Foo bar</div>
<div class="element">Foo bar baz</div>
<div class="last"><input type="text" /></div>
</div>
<div class="container">
<div class="element">Foo</div>
<div class="element">Foo bar</div>
<div class="element">Foo bar baz</div>
<div class="element">Foo</div>
<div class="element">Foo bar</div>
<div class="element">Foo bar baz</div>
<div class="last"><input type="text" /></div>
</div>
<button onclick="this.parentNode.classList.toggle('flex')">Toggle flex box</button>