Search code examples
htmlcsscss-grid

How can you fill columns with css grid?


In the example below, I want the left column elements, charlie, delta, echo divs to be full width (occupy both columns).

notes:

  • there might be an arbitrary number of right-column .r1, .r2 type elements (zero - N) so I won't know exactly how many rows should be on the right vs left
  • currently .a (acme) is affected by .r1's height, this is not desired! should have independent heights
  • please hit the "Run code snippet" button below to see whats going on, also an image below showing the kind of layout I'm interested in

.g {
  display: grid;
  gap: .25rem;
  grid-template-columns: 1fr 100px;
  grid-auto-flow: dense;
}

.gi {
  padding: 1rem;
  border: 1px solid;
  border-radius: .25rem;
  background-color: rgba(0, 0, 0, 0.1);
}

.l {
  grid-column: 1
}

.r { grid-column: 2 }
.r1 { grid-row: 1; height: 100px;}
.r2 { grid-row: 2}
<div class="g">
  <div class="gi l a">Acme</div>
  <div class="gi l b">Beta</div>
  <div class="gi l c">Charlie</div>
  <div class="gi l d">Delta</div>
  <div class="gi l e">Echo</div>
  <div class="gi r r1">Right 1</div>
  <div class="gi r r2">Right 2</div>
</div>

Image of desired layout:

example css grid showing columns


Solution

  • You have two challenges in your question:

    1. You want grid areas in the first column to expand into the second column when the row space is unoccupied.

    2. You want grid areas in one column to have variable heights, but without impacting the heights of grid areas in the other column.

    CSS Grid cannot do either automatically. You need to set additional CSS rules or use a script.