Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox: Keep element as last element before flex-wrap [duplicate]

Tags:

css

flexbox

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?

like image 652
Fynn Avatar asked Nov 14 '25 19:11

Fynn


1 Answers

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>
like image 147
Paulie_D Avatar answered Nov 17 '25 19:11

Paulie_D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!