I am trying to keep an element in the first row (as last element) of a list of wrapping elements. I know that this is possible using JS, but I am wondering if there is a CSS only solution to this. The closest I can get is putting the element in a separate container, but this results in an unwanted space between the elements:
.container {
display: flex;
}
.left {
display: flex;
flex-wrap: wrap;
}
.left > div {
padding: 1rem 1.5rem;
background: blue;
}
.right > div {
padding: 1rem 1.5rem;
background: red;
}
<div class="container">
<div class="left">
<div>Left 1</div>
<div>Left 2</div>
<div>Left 3</div>
<div>Left 4</div>
<div>Left 5</div>
<div>Left 6</div>
<div>Left 7</div>
<div>Left 8</div>
<div>Left 9</div>
</div>
<div class="right">
<div>More</div>
</div>
</div>
Basically, the red element should directly follow the last element in the first row of blue elements while the blue elements wrap inside their container. Is this possible with pure CSS?
With CSS-Grid this is possible but there are caveats. You have to specify a default width for your children and if there are not enough children to fill a row you may get gaps again.
Codepen Demo
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, auto));
}
.container div {
display: flex;
padding: 1rem 1.5rem;
background: blue;
white-space: nowrap;
}
.container .right {
grid-column-end: -1;
grid-row: 1;
padding: 1rem 1.5rem;
background: red;
}
<div class="container">
<div>Left 1</div>
<div>Left 2</div>
<div>Left 3</div>
<div>Left 4</div>
<div>Left 5</div>
<div>Left 6</div>
<div>Left 7</div>
<div>Left 8</div>
<div>Left 9</div>
<div class="right">More</div>
<div>Left 10</div>
<div>Left 11</div>
<div>Left 12</div>
</div>
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