htmlcssresponsive-designcss-grid

HTML elements do not span grid template areas properly (they span only one cell)


It is my first attempt us use responsive design using grid templates, following some example code I found. However my elements just use one grid cell, even if multiple contiguous cells use the same name.

Consider this primitive test (derived from the real code):

<html>
  <head>
    <title>Test</title>
    <style>
@media screen {
    .grid-1 {                           /* main grid */
        display: grid;
        grid-template-areas:
        'main main'
        'opt1 opt2'
        'opt3 opt3'
        'subm ...';
        gap: 10px;
    }

    .grid-1 * {
        /* adjust box sizing */
        margin: 0;
        box-sizing: border-box;
        background-color: #ccc;
    }
}

@media screen and (width < 60rem) {
    .grid-1 {
        grid-template-areas:
        'main main'
        'opt1 opt1'
        'opt2 opt2'
        'opt3 opt3'
        'subm ...';
    }
}
    </style>
  </head>
  <body>
    <div class="grid-1">
      <span grid-area="main">Main</span>
      <span grid-area="opt1">Options 1</span>
      <span grid-area="opt2">Options 2</span>
      <span grid-area="opt3">Options 3</span>
      <span grid-area="subm">Submit</span>
    </div>
  </body>
</html>

Debugging in Firefox the grid is shown like this (I added the background color in CSS for illustration after having made the screenshot):

Grid display in Firefox

(in the original code the <div> is a <form>, and the <span>s are `s)

Also note that adding more text into the elements does not change the assignment to grid cells.

Probably some beginner's mistake, but I don't get it.


Solution

  • The issue is that you're using grid-area as an HTML attribute on your elements, but that's not valid HTML and doesn't affect layout. grid-area should be set as a CSS property in your stylesheet, not as an HTML attribute.

    Update your HTML to use classes instead, like this:

    <div class="grid-1">
      <span class="main">Main</span>
      <span class="opt1">Options 1</span>
      <span class="opt2">Options 2</span>
      <span class="opt3">Options 3</span>
      <span class="subm">Submit</span>
    </div>
    

    Then, in your CSS, assign each class to a grid area:

    .main { grid-area: main; }
    .opt1 { grid-area: opt1; }
    .opt2 { grid-area: opt2; }
    .opt3 { grid-area: opt3; }
    .subm { grid-area: subm; }
    

    Now the elements will correctly span across the grid areas defined in your grid-template-areas.