0

I want the items in the last row of a CSS Grid to expand if there is not enough to fill the row naturally.

I can easily achieve this using Flexbox.

.container {
  display:flex;
  flex-wrap:wrap;
  margin:10px -5px;
}
.item {
  background:#eee;
  margin:0.5%;
  padding:40px;
  flex-grow:1;
  flex-basis:25%;
}
<h2>Flex auto fiting last row elements</h2>
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
</div>

The reason I want to do this with CSS Grid is it has grid-gap, which flexbox doesn't, which means using hacky code. You can see in my example the use of a negative margin on the container to offset the outer left and right margins of the items.

I have setup a codepen for the CSS Grid https://codepen.io/chrishoward/pen/ELdJxo and as you can see, the seventh item steadfastly refuses to expand to the width of the row.

I've spent hours on this today including CSS Tricks and Rachel Andrew's excellent examples, so not even sure if this is possible.

Thank you

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • Do you know how many items should fit per row (here 2 except maybe last row) and if each of them occupy only 1 column (no `span 2` here and there)? If yes, then `:nth-child(odd) { grid-column: 1 / -1 }` solves your problem – FelipeAls May 17 '18 at 10:27
  • No this isn't possible AFAICT. – Paulie_D May 17 '18 at 11:44
  • Dupes - https://stackoverflow.com/questions/45435444/css-grid-dynamically-span-the-last-column and https://stackoverflow.com/questions/45435444/css-grid-dynamically-span-the-last-column – Paulie_D May 17 '18 at 11:51
  • Not possible. Track walls (for columns and rows) block grid areas from stretching across the line. Flex lines don't have this problem ([more details](https://stackoverflow.com/q/50234112/3597276)). – Michael Benjamin May 17 '18 at 14:20
  • For a deeper understanding of the problem, here's the reverse scenario, showing why it works in flexbox. https://stackoverflow.com/q/42176419/3597276 – Michael Benjamin May 17 '18 at 14:22
  • @Michael_B Track walls can be spanned manually tho from row to row as seen in this example: https://gridbyexample.com/examples/example20/ So it is possible to do this manually, but you're saying there is no way to do it automatically? – Chris Howard May 19 '18 at 12:17
  • This question not actually a dupe of https://stackoverflow.com/questions/50234112/aligning-grid-items-across-the-entire-row-column-like-flex-items-can, the other question is asking how to center content, this question is asking how to expand content. They may rely on the same technical underpinnings but they are asking for distinct outcomes. @Paulie_D has better suggestions for dupes. – James McMahon Sep 11 '19 at 15:24

0 Answers0