htmlcssresponsive-designcss-grid

Why does grid-template-areas break when combining minmax() and auto-fit in CSS Grid?


I’m trying to create a responsive layout using CSS Grid.

The grid should have a header, main content, and a footer. I’m using grid-template-areas combined with auto-fit and minmax() to make the layout flexible.

But when I resize the browser, the areas break, and sometimes main and footer overlap or don’t span the full width.

problem

Problem

I want each area (header, main, footer) to always be on its own row, and the grid columns should expand and shrink only within the row’s width, without breaking the layout.

Is this a limitation when using grid-template-areas with auto-fit and minmax()? Or is there a correct way to make the rows behave as expected while keeping it responsive?

.container {
  display: grid;
  grid-template-areas:
    "header"
    "main"
    "footer";
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 10px;
  height: 100vh;
}

header { grid-area: header; background: lightcoral; padding: 20px; }
main { grid-area: main; background: lightblue; padding: 20px; }
footer { grid-area: footer; background: lightgreen; padding: 20px; }

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
<body>
  <div class="container">
    <header>Header</header>
    <main>Main Content</main>
    <footer>Footer</footer>
  </div>
</body>


Solution

  • You are facing this issue because of :
    gird-template-columns: repeat(auto-fit ,minmax(300px,1fr));

    This creates multiple columns which ins't necessary if you want each section on its own row spanning the full width.
    grid-template-columns setup is more suitable for layouts with multiple items in a row, like cards or tiles-not full-width rows.

    As for you'r issue you should remove the grid-template-columns declaration and instead define grid-template-rows to structure your layout vertically. A good setup would be grid-template-rows: auto 1fr auto;, which ensures the header and footer take up only as much height as needed, while the main section expands to fill the remaining space. Keep using grid-template-areas to semantically organize your layout as "header" "main" "footer".