Search code examples
htmlcssgrid-layoutcss-grid

How do you get grid-column-start and span to work together?


I'm creating a table and have most of it created using the grid function of css, but am running into a problem when adding categories on top. The number of categories will be dynamic, so I'm trying to avoid hardcoding in css styles for each number of categories.

I see the grid-column-start property, but although I want it to start on column 2 and span 2 columns, it doesn't do this.

How can I fix this? Thanks.

.wrapper {
  display: grid;
  grid-template-columns: repeat(5, 100px);
}

.box {
  background-color: #444;
  color: #fff;
  outline: 2px solid #000;
  padding: 5px;
}

.category {
  grid-row: 1;
  grid-column-start: 2 / span 2;
}

.header {
  grid-row: 2;
}


/*hacks to manually place grid boxes*/

.category1 {
  grid-row: 1;
  grid-column: 2 / span 2;
}

.category2 {
  grid-row: 1;
  grid-column: 4 / span 2;
}

.row1 {
  grid-row: 3;
}

.row2 {
  grid-row: 4;
}
What I want:
<p>
  <div class="wrapper">
    <div class="box category1">Category</div>
    <div class="box category2">Category</div>

    <div class="box header">#</div>

    <div class="box header">header1a</div>
    <div class="box header">header1b</div>

    <div class="box header">header2a</div>
    <div class="box header">header2b</div>

    <div class="box data row1">1</div>

    <div class="box data row1">data1a</div>
    <div class="box data row1">data1b</div>

    <div class="box data row1">data2a</div>
    <div class="box data row1">data2b</div>
  </div>
</p>
<p></p>
What I have:
<p>
  <div class="wrapper">
    <div class="box category">Category</div>
    <div class="box category">Category</div>

    <div class="box header">#</div>

    <div class="box header">header1a</div>
    <div class="box header">header1b</div>

    <div class="box header">header2a</div>
    <div class="box header">header2b</div>

    <div class="box data">1</div>

    <div class="box data">data1a</div>
    <div class="box data">data1b</div>

    <div class="box data">data2a</div>
    <div class="box data">data2b</div>
  </div>
</p>


Solution

  • The following syntax is invalid:

    grid-column-start: 2 / span 2;
    

    The only permitted value for this property is a grid line, like this:

    grid-column-start: 2;
    

    The same syntax applies to all four line-based placement longhand properties:

    • grid-row-start
    • grid-row-end
    • grid-column-start
    • grid-column-end

    source: https://www.w3.org/TR/css3-grid-layout/#line-placement


    The shorthand properties for the properties above are:

    • grid-row
    • grid-column

    Because these shorthand properties represent both -start and -end properties, they can accept two values.

    This rule:

    • grid-column: 2 / span 2

    is valid and breaks down to:

    • grid-column-start: 2
    • grid-column-end: span 2

    source: https://www.w3.org/TR/css3-grid-layout/#placement-shorthands