Andy Ray
Andy Ray

Reputation: 32066

Dynamic CSS grid with template-columns: auto and full-width row

I'm trying to build a CSS grid dynamically from some data. I'm trying to achieve a layout like:

   | a | b | c | d
---+---+---+---+---
full width
---+---+---+---+--
 x | 1 | 2 | 3 | 4
---+---+---+---+--
 y | 2 | 3 | 4 | 5

Where I have a dynamic number of columns, and a full width row that spans all of the columns.

The markup I'm generating (in a loop in my template) ends up looking something like:

<div class="wrapper">
  <div class="box header">header 1</div>
  <div class="box header">header 2</div>
  <div class="box header">header 3</div>
  <div class="box header">header 4</div>
  <div class="box full-width">full width</div>
</div>

And I'm attempting to style it by marking the full-width row with:

    .full-width {
        grid-column: 1 / -1;
        grid-row: 2;
    }

My understanding is that the 1 / -1 is supposed to make the row span from the first column to the last. In this case, it doesn't, and the width of the row is unaffected. You can see this issue live on Codepen.

Upvotes: 0

Views: 5666

Answers (1)

anatolhiman
anatolhiman

Reputation: 1859

Your header rule sets row to 1, and this limits your grid layout. You need at least 3 rows in order to have one for the header, and two for the full-width element.

  1. Start by removing the header rule completely.

  2. Then add grid-template-rows to the wrapper.

  3. Change your wrapper to use repeat(), this makes the horizontal span work as expected:

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  background-color: #fff;
  color: #444;
}
  1. In order to make full-width span 2 rows you need at least 3 rows in total. Plus you need to declare your grid-row span like this:
.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  background-color: #fff;
  color: #444;
  grid-template-rows: repeat(3, minmax(0, 1fr));
}

.full-width {
  grid-column: 1 / -1;
  grid-row: span 2 / span 2;
}
  1. If you want an empty node at the top left corner of the grid, we need to increase the amount of columns to 5. We also need an extra class that pushes the first grid child one column towards the right (the other children will be pushed along):
.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  background-color: #fff;
  color: #444;
  grid-template-rows: repeat(3, minmax(0, 1fr));
}

.wrapper:first-child {
  grid-column-start: 2;
}

Upvotes: 2

Related Questions