0

I am trying to remove the dead space in display: grid when certain elements are at a taller height. Meaning that each element may need to be on a different y-axis, to account for any dead-space in the grid. Though, this must be dynamic, as I would like to display user profiles, leaving some elements slightly taller than others on the row.

Currently, I am able to get each element to respectively have a the height needed to fit it's content, but as a result of everything staying on the same y-axis, dead space is automatically added below each element in order to account for the height differences. See below for a visual.

dead space in grid

Using VisBug, I am able to move them by hand, in order to get a visual of what I need.

The goal

Currently, in the first image, I have used the grid-auto-flow: dense CSS property, which sets the height of each element to it's children height, however, each element with blank space above it, will need to move up. (See second image). The goal is to remove all of the blank space dynamically, whilst also allowing a new element/div to be added, and pertain this grid behaviour.

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  align-items: start;
  grid-auto-flow: dense;
}

.profile-listing {
  background-color: #f2f2f2;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 2px 2px 5px #ccc;
}

@media only screen and (max-width: 768px) {
  .grid-container {
    grid-template-columns: 1fr 1fr;
  }
}
<div class="grid-container">
  <div class="profile-listing">Profile 1</div>
  <div class="profile-listing">Profile 2 <br> hello </div>
  <div class="profile-listing">Profile 3</div>
  <div class="profile-listing">Profile 4</div>
  <div class="profile-listing">Profile 5<br/>with<br/>more<br/>content</div>
  <div class="profile-listing">Profile 6</div>
  <div class="profile-listing">Profile 7 <br> test <br> content </div>
  <div class="profile-listing">Profile 8</div>
  <div class="profile-listing">Profile 9 <br> hi </div>
  <div class="profile-listing">Profile 10</div>
  <div class="profile-listing">Profile 11</div>
  <div class="profile-listing">Profile 12</div>
</div>
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Cohen
  • 2,375
  • 3
  • 16
  • 35

0 Answers0