0

I have a grid that's two columns side by side. However, there's an odd number of elements, so I would like to offset the right column so it's centered vertically against the left column.

What would be the best way to do that using grid?

Here's an example how i want the layout to look:

enter image description here

Here's an example: https://codepen.io/patricktm/pen/JjMzQWj

body {
  max-width: 1000px;
  margin: auto;
}

.grid-item {
  background-color: #ccc;
  border: 1px solid;
  height: 200px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1em;
}
<body>
  <div class='grid'>
    <div class='grid-item'>1</div>
    <div class='grid-item'>2</div>
    <div class='grid-item'>3</div>
    <div class='grid-item'>4</div>
    <div class='grid-item'>5</div>
    <div class='grid-item'>6</div>
    <div class='grid-item'>7</div>
  </div>
</body>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
patricko
  • 831
  • 4
  • 16
  • 34

1 Answers1

1

This layout isn't really feasible with Grid because there are fix row tracks that prevent the free flow of items across the column.

You're basically asking the top item in the second column to somehow space itself down in the first row track and cross into the second track, pushing down the other items along the way.

Grid doesn't work this way. The matter is discussed in detail in this post:

One simple way to make this layout work uses flexbox, which has no column or row tracks crossing through the flex lines. (You'll have to tweak it though, as my simple example will only work on taller screens. On shorter screens additional columns will be generated.)

.grid {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: center; /* key */
  height: 100vh;
  gap: 1em;
}

.grid-item {
  background-color: #ccc;
  border: 1px solid;
  height: 21%; /* prevents a 5th item in the column */
}

body {
  max-width: 1000px;
  margin: auto;
}
<div class='grid'>
  <div class='grid-item'>1</div>
  <div class='grid-item'>2</div>
  <div class='grid-item'>3</div>
  <div class='grid-item'>4</div>
  <div class='grid-item'>5</div>
  <div class='grid-item'>6</div>
  <div class='grid-item'>7</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701