Search code examples
csscss-grid

Implicit grid-area doesn't work as expected


given this html

<div class="parent">
  <div class="first">1</div>
  <div class="second">2</div>
  <div class="third">3</div>
  <div class="fourth">4</div>
</div>

and this css

.parent { 
  display: grid;
  grid-template-areas: 
  'first second'
  'third third'
  'fourth fourth'
}

I expected the grid area "third" and "fourth" to implicitly have 1 column, which would render like so

enter image description here

I understand I can fix this by specifying grid-area, curious if theres another approach?

https://jsfiddle.net/qgdh2b8a/2/


Solution

  • This isn't a completely different approach, but you could use grid-column and not use grid-template-areas entirely. This solution also uses grid-template-columns.

    .parent { 
      display: grid;
      grid-gap: 3px;
      /* Defines two columns */
      grid-template-columns: 1fr 1fr;
    }
    
    .parent > div {
      /* Visibility and styling */
      background-color: black;
      color: white;
      padding: 1rem;
      text-align: center;
      font-family: sans-serif;
    }
    
    .third, .fourth {
      /* Sets the column that the item should span */
      grid-column: 1 / -1;
    }
    <div class="parent">
      <div class="first">1</div>
      <div class="second">2</div>
      <div class="third">3</div>
      <div class="fourth">4</div>
    </div>

    Here, the third and fourth classes have this style applied: grid-column: 1 / -1. The slash specifies the amount of columns that the element should span. 1 is the first column and -1 is the first from last (the last column).

    Examples:

    • grid-column: 3 Sets the grid column to 3.
    • grid-column: 1 / 3 Sets the element to span columns 1 through 3.
    • grid-column: 1 / -2 Sets the element to span columns 1 through the 2nd last one.