Skip to content

CSS Grid

CSS Grid provides a native two-dimensional layout system, eliminating the need for float-based layouts and complex flexbox workarounds.

/* Float-based grid */
.container {
overflow: hidden; /* clearfix */
}
.row::after {
content: '';
display: table;
clear: both;
}
.column {
float: left;
width: 33.333%;
padding: 0 15px;
box-sizing: border-box;
}
.column:nth-child(3n + 1) {
clear: left;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.column {
width: 50%;
}
.column:nth-child(3n + 1) {
clear: none;
}
.column:nth-child(2n + 1) {
clear: left;
}
}

Problems:

  • Requires clearfix hacks
  • Manual width calculations with percentages
  • Complex nth-child selectors for row clearing
  • No native gap/gutter support
  • Cannot easily create unequal column layouts
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 30px;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.container {
grid-template-columns: repeat(2, 1fr);
}
}

Benefits:

  • No clearfix needed
  • Built-in gap support
  • Fractional units (fr) for flexible sizing
  • Simple responsive changes
  • Clean, declarative syntax
.page {
display: grid;
grid-template-areas:
'header header header'
'nav main aside'
'footer footer footer';
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header {
grid-area: header;
}
.nav {
grid-area: nav;
}
.main {
grid-area: main;
}
.aside {
grid-area: aside;
}
.footer {
grid-area: footer;
}
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}

Cards automatically wrap and fill available space—no media queries needed.

.parent {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.child {
display: grid;
grid-column: span 2;
grid-template-columns: subgrid; /* Inherits parent's column tracks */
}

Supported in all modern browsers. See caniuse.com/css-grid.

Subgrid has slightly less support. See caniuse.com/css-subgrid.

  • Grid layout is hardware-accelerated
  • Avoid deeply nested grids for best performance
  • Use grid-template-areas for complex layouts—easier to maintain
  • auto-fit and auto-fill are computed at layout time

Use CSS Grid when:

  • Building two-dimensional layouts (rows AND columns)
  • Creating complex page structures
  • You need built-in gap/gutter support
  • Building card grids with equal-height items
  • Layout depends on both row and column positioning

Use Flexbox when:

  • One-dimensional layout (row OR column)
  • Content size should determine layout
  • You need to align items within a container