1

I am in the process of learning CSS grid. Now I am struggling to align the grid's content.

.grid-container {
  background-color: grey;
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  justify-content: end;
}

.grid-item {
  background-color: green;
  grid-column: span 7 / span 7;
}
<div class="grid-container">
  <div class="grid-item">My item</div>
</div>

Let's go through the rules.

On the container:

  • grid-template-columns: repeat(12, minmax(0, 1fr)): As far as I understood, this creates 12 equal columns based on the space available.
  • justify-content: end: Shouldn't this align the grid items so they are flush against the end (right side) of the grid container?

On the child:

  • grid-column: span 7 / span 7: Sizes the element to take up seven fractions of space from the twelve fractions (columns) available.

Why is the grid item not aligned against the end of the container?

Sven
  • 12,997
  • 27
  • 90
  • 148

1 Answers1

2

What you are looking for is grid-column: span 7 / -1. span 7 columns but start from the last one:

.grid-container {
  background-color: grey;
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  /* justify-content: end; will do nothing */
}

.grid-item {
  background-color: green;
  grid-column: span 7 / -1;
}
<div class="grid-container">
  <div class="grid-item">My item</div>
</div>

Also not that justify-content doesn't align grid items like it does in Flexbox. it align the grid tracks and justify-items align grid items inside the tracks.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • I am truly amazed! My mental model of grid was wrong. Your answer helped me a lot to understand it better. – Sven Jul 03 '23 at 12:50