Search code examples
csscss-grid

Can a grid cell span every column without specifying the number of columns?


I have a grid with a dynamically generated number of rows and columns. The cells are placed individually with grid-column-start.

I also have accompanying headings which need span every column. I would expect grid-column-start: 1; grid-column-end: -1 to produce this behaviour. However, it only does so if the number of columns is specified in advance with grid-template-columns.

See the following demonstration:

.grid {
  display: grid;
  grid-gap: 5px;
}

.grid--three {
  grid-template-columns: auto auto auto;
}

.grid--auto {
  grid-auto-columns: auto;
}

.grid-heading {
  background: pink;
  grid-column-start: 1;
  grid-column-end: -1;
  padding: 5px;
}

.grid-cell {
  background: lightblue;
  padding: 5px;
}

.grid-cell--1 {
  grid-column-start: 1;
}

.grid-cell--2 {
  grid-column-start: 2;
}

.grid-cell--3 {
  grid-column-start: 3;
}
<h3>Three column grid</h3>

<div class="grid grid--three">
  <div class="grid-heading">
    My heading
  </div>
  <div class="grid-cell">
    one
  </div>
  <div class="grid-cell">
    two
  </div>
  <div class="grid-cell">
    three
  </div>
</div>

<h3>Any column grid</h3>

<div class="grid grid--auto">
  <div class="grid-heading">
    My heading
  </div>
  <div class="grid-cell grid-cell--1">
    one
  </div>
  <div class="grid-cell grid-cell--2">
    two
  </div>
  <div class="grid-cell grid-cell--3">
    three
  </div>
</div>

Is it possible to get full column spanning behaviour without prescribing the number of columns?


Solution

  • Unfortunately, no. This is not possible with the current version of CSS Grid (Level 1).

    For a grid area to expand across all columns or rows, using the negative integer method (1 / -1), you'll need an explicit grid container.

    From the specification:

    7.1. The Explicit Grid

    Numeric indexes in the grid-placement properties count from the edges of the explicit grid.

    Positive indexes count from the start side (starting from 1 for the start-most explicit line), while negative indexes count from the end side (starting from -1 for the end-most explicit line).

    and here...

    8.3. Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties

    If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid.