Search code examples
htmlcsscss-gridsemantic-markup

CSS grid and semantic HTML


I'm learning CSS grid and while trying to do my layout and use semantic html at the same time I run into some problems

https://codepen.io/oscarryz/pen/oNNBKyd

So basically I'm doing grid as 3x3 with empty space on the left and right and the content in the middle

.grid-container {
  display: grid;
  grid-template-columns: 1fr 40em 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    " . header . "
    " . content . "
    " . footer . ";
}

.header {
  grid-area: header;
}

.content {
  grid-area: content;
}

.footer {
  grid-area: footer;
}

.header, .content, .footer {
  border: 1px solid red;
}
<div class="grid-container">
  <header>
    <div class="header">header</div>
  </header>
  <main>
    <div class="content">content</div>
  </main>
  <footer>
    <div class="footer">footer</div>
  </footer>
</div>

As can be seen in the codepen above, this is not working. If I remove the semantic tags it works, obviously there must be a correct way of doing this


Solution

  • Grid templates are for direct descendants.

    The semantic elements should be referenced by tagname, not class:

    /* changed from .header, which is a _child_ of header */
    header {
      grid-area: header;
    }
    
    /* changed from .content, which is a _child_ of main */
    main {
      grid-area: content;
    }
    
    /* changed from .footer, which is a _child_ of footer */
    footer {
      grid-area: footer;
    }
    

    Corrected codepen here: https://codepen.io/c_bergh/pen/eYYvOmG