Home > Software engineering >  CSS Grid: column-placed item going to next row
CSS Grid: column-placed item going to next row

Time:10-22

I'm trying to achieve a grid showing position, name, evolution and score of users.

This list is dynamic, meaning I don't know how many rows I'm gonna have at the end.

Another constraint is that I can't change the order of elements in HTML.

As you can see in the snippet below, when I place items by column number, .name goes to the next row instead of staying on the current one, and I don't know why...

body {
  background-color: darkslategrey;
  color: white;
}

.container {
  display: grid;
  grid-template-columns: repeat(3, auto);
  gap: 10px;
  text-align: center;
}

.name,
.evolution,
.score {
  border-top: 1px solid white;
  border-bottom: 1px solid white;
}

.position {
  grid-column: 1 / span 3;
}

.name {
  grid-column: 1;
}

.evolution {
  grid-column: 2;
}

.score {
  grid-column: 3;
}
<div >
  <div >1st</div>
  <div > 2</div>
  <div >85pts</div>
  <div >Jack</div>
  <div >2nd</div>
  <div > 3</div>
  <div >82pts</div>
  <div >Kate</div>
  <div >3rd</div>
  <div >-2</div>
  <div >80pts</div>
  <div >Sawyer</div>
  <!-- and many more, this list is dynamic -->
</div>

What am I missing here ?

CodePudding user response:

The grid is filling in the order in which you have given it the HTML elements

But you'd like it to fill up any spare space if it can. CSS has the grid-auto-flow property which will make this happen. It'll spot the empty cell on row two and put Jack into it for example.

body {
  background-color: darkslategrey;
  color: white;
}

.container {
  display: grid;
  grid-template-columns: repeat(3, auto);
  grid-auto-flow: dense;
  gap: 10px;
  text-align: center;
}

.name,
.evolution,
.score {
  border-top: 1px solid white;
  border-bottom: 1px solid white;
}

.position {
  grid-column: 1 / span 3;
}

.name {
  grid-column: 1;
}

.evolution {
  grid-column: 2;
}

.score {
  grid-column: 3;
}
<div >
  <div >1st</div>
  <div > 2</div>
  <div >85pts</div>
  <div >Jack</div>
  <div >2nd</div>
  <div > 3</div>
  <div >82pts</div>
  <div >Kate</div>
  <div >3rd</div>
  <div >-2</div>
  <div >80pts</div>
  <div >Sawyer</div>
  <!-- and many more, this list is dynamic -->
</div>

  • Related