DecPK
DecPK

Reputation: 25401

How to make grid-items take only remaining space from rows?

I'd like to make grid-item number 2, 3, 4 squeeze to top, It shouldn't start from its natural grid-lines. I want to remove horizontal extra space between grid-item (2-3) and grid-item 3-4. How can I achieve this?

Grid Item 1 can be of any height. It is dynamic.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.container>div {
  background-color: teal;
  border-radius: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  color: whitesmoke;
}

.item1 {
  grid-row: 1/4;
  height: 500px;
}

.item2,
.item3,
.item4 {
  height: 100px;
}
<div class="container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
</div>

Upvotes: 0

Views: 288

Answers (2)

The simplest somlution would be to add another row that can expand.

.item1 {
  grid-row: 1/5;
  height: 500px;
}

grid-row: 1/5 means that the grid will have 4 rows. This allows 3 items to flow to the top on the right side, and the forth row can expand as needed.

Upvotes: 2

Anya
Anya

Reputation: 1418

I like to think about grids are abstractional layers and not fixed structures. This way you freely place your divs into the grid blocks and not BE the grid blocks.

Following this pattern, defining a grid of 8 rows, for example, and telling your divs to occupy "x" rows could do the trick. Feel free to play with the rows number and spans to better suit your needs. :)

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.container>div {
  background-color: teal;
  border-radius: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  color: whitesmoke;
}

.item1 {
  grid-row: 1/8;
  height: 500px;
}

.item2,
.item3,
.item4 {
  grid-row: span 2;
  height: 100px;
}
<div class="container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
</div>

This is the sketch of the idea: enter image description here

Upvotes: 1

Related Questions