Search code examples
csscss-grid

CSS grid-template-areas no auto column span


I'm new using CSS grids and watched a few videos about it and in all of them I saw the property grid-template-areas which seems to be cool because you just define the same name to span columns or rows for the grid item, but it hasn't worked for me, this is my html:

body {
  display: grid;
  grid-template-areas: "header header" "adds content";
  grid-template-rows: 3em auto;
  grid-template-columns: 20em 1fr;
}

.top-menu {
  grid-area: "header";
  grid-column: span 2;
  background-color: #B6B0A9;
}
<div class="top-menu">
  <ul>
    <li><a href="#" class="menu-item">Hi</a></li>
    <li><a href="#" class="menu-item">Lo</a></li>
  </ul>
</div>

When I just use grid-area:"header"; the div with the class top-menu doesn't span in the two columns, that's why I had to use grid-column:span 2; is there something that I've missed about grid-template-areas behavior? Or this isn't the proper configuration?


Solution

  • That's something I also struggled with when starting with grid, it's easy to overlook:

    when using grid-area you don't use " to define the area. So instead of "header" use header

    body {
      display: grid;
      grid-template-areas: "header header" "adds content";
      grid-template-rows: 3em auto;
      grid-template-columns: 20em 1fr;
    }
    
    .top-menu {
      grid-area: header;
      grid-column: span 2;
      background-color: #B6B0A9;
    }
    
    .adds {
      grid-area: adds;
    }
    
    .content {
      grid-area: content;
    }
    <div class="top-menu">
      <ul>
        <li><a href="#" class="menu-item">Hi</a></li>
        <li><a href="#" class="menu-item">Lo</a></li>
      </ul>
    </div>
    
    <div class="adds">
      Some adds
    </div>
    <div class="content">
      Here is some content
    </div>