Marie Kaya

Author

I am so happy, my dear friend, so absorbed in the exquisite sense of mere tranquil existence, that I neglect my talents.

Main Menu

10 Essential CSS Grid Layout Techniques for Modern Websites

CSS Grid is a powerful tool for creating modern, responsive web layouts. It simplifies designing with rows and columns, offering flexibility and precision. Here’s what you’ll learn:

  • Basic Grid Setup: Define rows and columns with grid-template.
  • Flexible Layouts: Use fr units for proportional spacing and minmax() for responsive designs.
  • Dynamic Columns: Leverage auto-fit and auto-fill for layouts that adapt to content.
  • Named Grid Areas: Organize layouts visually with grid-template-areas.
  • Content Alignment: Align items with properties like align-items and justify-items.
  • Spacing with gap: Simplify row and column spacing.
  • Nested Grids: Create grids within grids for complex designs.
  • Flow Control: Manage item placement with grid-auto-flow.
  • Accessibility: Ensure screen-reader-friendly layouts with logical source order.

Quick Comparison of Flexbox vs. CSS Grid

Flexbox

Feature CSS Grid Flexbox
Layout Type Two-dimensional (rows + cols) One-dimensional (row/col)
Best Use Case Page layouts Component alignment
Design Approach Layout-first Content-first
Positioning Control Precise in both dimensions Flexible in one dimension

CSS Grid works best for overall page layouts, while Flexbox excels at aligning elements within components. Dive into these techniques to create clean, efficient, and responsive designs.

Learn CSS Grid – A 13 Minute Deep Dive

1. Basic Grid Setup with grid-template

Start building a CSS Grid layout by using the grid-template shorthand to define rows and columns.

First, set display: grid on your container. Then, use grid-template to configure your grid. Here’s an example of a simple two-column layout:

.container {
  display: grid;
  grid-template-columns: 1fr 250px;
}

In this setup, the first column is flexible (1fr), while the second column has a fixed width of 250px – perfect for a sidebar.

You can mix different unit types in grid-template for more control:

Unit Type Purpose Example Value
Pixels (px) Fixed-width columns 250px
Fractions (fr) Flexible space distribution 1fr
Percentages (%) Relative sizing 50%
Auto Content-based sizing auto

For responsive designs, combining minmax() with the repeat() function creates grids that adjust to various screen sizes. For instance:

.responsive-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(10rem, 100%), 1fr));
}

You can also name grid lines for more precise placement of items:

.named-grid {
  display: grid;
  grid-template-columns: [sidebar-start] 250px [sidebar-end content-start] 1fr [content-end];
}

Pro Tip: To prevent columns from collapsing into tiny sizes on smaller screens, use minmax(10px, 1fr) instead of just 1fr.

If you don’t define grid tracks explicitly, the browser will create implicit tracks based on grid-auto-rows and grid-auto-columns.

Up next, learn how fractional units can make your grid designs more dynamic.

2. Using fr Units for Grid Columns

The fr unit is a handy tool for creating flexible CSS Grid layouts. It helps divide available space proportionally without causing overflow problems.

Here’s an example of how it works:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;  /* Three equal-width columns */
  gap: 20px;
}

With fr, the browser calculates free space by subtracting gutter widths and dividing it among the columns.

You can also mix fr values to create layouts with varying column widths:

.asymmetric-grid {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;  /* Middle column is twice as wide as the others */
}
Layout Type Grid Template Result
Equal columns 1fr 1fr 1fr Three columns of equal width
Sidebar layout 200px 1fr Fixed-width sidebar, flexible content
Magazine style 1fr 2fr 1fr Wider center column
Mixed units 300px 10% 1fr 1fr Combines fixed, percentage, and flexible widths

You can also create hybrid layouts by combining fr units with fixed widths:

.hybrid-layout {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;  /* Fixed sidebar with two flexible columns */
  gap: 16px;
}

Tip: To avoid issues with content that doesn’t scale well, use minmax to set boundaries:

.safe-grid {
  display: grid;
  grid-template-columns: minmax(200px, 1fr) 2fr;
}

This ensures your layout stays responsive while keeping content readable across different screen sizes. The fr unit also automatically accounts for grid gaps, making it a great choice for layouts where percentage-based units might cause overflow.

3. Responsive Grids with minmax()

The minmax() function is a powerful tool for creating grids that adapt to different screen sizes. It lets you define a track’s minimum and maximum size, ensuring flexibility without sacrificing design.

Here’s an example of a responsive card grid:

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(100%, 250px), 1fr));
  gap: 1rem;
}

This setup ensures cards maintain consistent dimensions while avoiding horizontal scrollbars, regardless of the screen size.

For content-focused layouts, consider this approach:

.article-layout {
  display: grid;
  grid-template-columns: minmax(1rem, 1fr) minmax(auto, 70ch) minmax(1rem, 1fr);
  gap: 1rem;
}

This three-column layout balances readability by capping the content width at 70 characters, while offering flexible margins and consistent padding on smaller screens.

Layout Type Grid Template Best Use Case
Card Grid repeat(auto-fill, minmax(250px, 1fr)) Product listings, image galleries
Article Layout minmax(1rem, 1fr) minmax(auto, 70ch) minmax(1rem, 1fr) Blog posts, documentation
Tile Layout repeat(auto-fit, minmax(200px, 1fr)) Dashboard widgets, feature sections

Another example of a flexible grid:

.responsive-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(10rem, 100%), 1fr));
  gap: 16px;
}

“Defines a size range greater than or equal to min and less than or equal to max.” – CSS spec

Pro tip: When using auto-fit with minmax() for dynamic content, be cautious of items stretching unexpectedly due to variable widths. This method is a great starting point for advanced dynamic column strategies, which will be covered in the next section.

4. Dynamic Columns with auto-fit and auto-fill

Using minmax() is great for responsive designs, but auto-fit and auto-fill take it a step further by simplifying column management. These keywords, when paired with the repeat() function, allow columns to adjust automatically based on the container’s width. Here’s the difference: auto-fill creates columns that fill unused space, even if they’re empty, while auto-fit collapses empty columns and redistributes the space among existing ones.

Take a look at how this works in practice:

/* auto-fill example */
.gallery-fill {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}

/* auto-fit example */
.gallery-fit {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}
Property Behavior Best Use Case
auto-fill Creates consistent column sizes, even with empty spaces Product catalogs, image galleries with fixed widths
auto-fit Adjusts columns to fill available space Full-width layouts, responsive card designs

You can also combine these properties with the min() function for even more flexibility:

.responsive-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(10rem, 100%), 1fr));
  gap: 16px;
}

“auto-fill FILLS the row with as many columns as it can fit… The newly added columns can and may be empty, but they will still occupy a designated space in the row.” – Sara Soueidan

So, when should you use each? Opt for auto-fit if you want to avoid empty columns and make use of all available space. On the other hand, auto-fill is perfect for maintaining consistent spacing, even if some columns end up empty.

For better browser compatibility, you can add a fallback by combining a calc()-based definition with the min() approach:

.gallery {
  display: grid;
  /* Fallback for browsers without min() support */
  grid-template-columns: repeat(auto-fill, minmax(calc(10% + 7.5rem), 1fr));
  grid-template-columns: repeat(auto-fill, minmax(min(10rem, 100%), 1fr));
}

This ensures your layout remains functional, even in browsers that don’t yet support min().

5. Named Grid Areas with grid-template-areas

Named grid areas offer a clear way to create complex layouts using a visual, ASCII-art style syntax. This approach has been supported by major browsers since March 2017.

The grid-template-areas property allows you to define layouts with named cells, making the structure easy to understand. Here’s an example of the classic “Holy Grail” layout:

.container {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main aside"
    "footer footer footer";
  grid-template-rows: 80px 1fr 60px;
  grid-template-columns: 200px 1fr 200px;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }

To leave some grid areas empty, use dots:

.asymmetric-layout {
  grid-template-areas:
    "header header"
    "nav    main"
    ".      footer";
}

Why Use Named Grid Areas?

Feature Advantage Ideal For
Visual Syntax Simplifies layout visualization Complex page structures
Centralized Control Easier layout management Responsive designs
Empty Cell Support Flexible space usage Asymmetric layouts

Important Rules for Grid Areas:

  • Grid areas must always form rectangles.
  • Each row should have the same number of cells.
  • Area names need to stay consistent throughout.

“What I like about grid areas is that they provide us with a visualization of the grid in CSS.” – Ahmad Shadeed

For responsive designs, you can redefine grid areas at different breakpoints. Here’s an example:

@media (max-width: 768px) {
  .container {
    grid-template-areas:
      "header"
      "main"
      "sidebar"
      "footer";
    grid-template-columns: 1fr;
  }
}

This method keeps your layout centralized and easier to maintain, especially for responsive and complex designs. Just ensure your HTML’s source order aligns with the visual layout for accessibility.

Next, we’ll explore how to align content within grid cells for complete layout control.

sbb-itb-361ab2b

6. Content Alignment in Grid Cells

CSS Grid alignment takes your layouts to the next level by offering precise control over content placement. This is essential for creating polished and responsive designs.

Basic Alignment Properties

CSS Grid alignment operates along two axes:

  • Block axis (vertical): Controlled by align-items and align-self.
  • Inline axis (horizontal): Controlled by justify-items and justify-self.

Here’s how you can apply basic alignment:

.grid-container {
  display: grid;
  align-items: center;     /* Aligns all items vertically */
  justify-items: start;    /* Aligns all items horizontally */
}

.special-item {
  align-self: end;         /* Custom vertical alignment for one item */
  justify-self: center;    /* Custom horizontal alignment for one item */
}

Alignment Property Values

Property Common Values Purpose
align-items / justify-items start, end, center, stretch Sets default alignment for all grid items
align-self / justify-self start, end, center, stretch Custom alignment for a specific grid item
place-items center center, start end Combines vertical and horizontal alignment

Advanced Alignment Techniques

For more control over your grid layout, you can use advanced alignment properties:

.grid-container {
  display: grid;
  height: 100vh;
  place-items: center;              /* Centers items both vertically and horizontally */
  align-content: space-between;     /* Distributes rows vertically */
  justify-content: space-around;    /* Distributes columns horizontally */
}

Key Points to Remember

Here are some important details when working with CSS Grid alignment:

  • The default value for both align-items and justify-items is stretch.
  • Items with intrinsic aspect ratios will default to start alignment.
  • Unlike Flexbox, Grid supports justify-self and justify-items for individual and group alignment.

For responsive designs, adjust alignment properties at different breakpoints:

.grid-container {
  display: grid;
  place-items: center;
}

@media (max-width: 768px) {
  .grid-container {
    place-items: start stretch;  /* Adjusts alignment for smaller screens */
  }
}

7. Grid Spacing with gap

The gap property simplifies spacing between grid items by applying directly to the grid container. This avoids the headaches of margin-based spacing and ensures uniform gutters without extra math.

Basic Gap Usage

Add consistent spacing between rows and columns with a single line:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;  /* Applies equal spacing to rows and columns */
}

Need different spacing for rows and columns? Use two values:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30px 20px;  /* First value: row-gap, second value: column-gap */
}

Fine-Tuning with Individual Gap Properties

For precise control, split gap into row-gap and column-gap:

.grid-container {
  display: grid;
  row-gap: 2rem;      /* Space between rows */
  column-gap: 1.5rem; /* Space between columns */
}

Making Gaps Responsive

Use dynamic units like viewport widths or percentages for flexible spacing:

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: clamp(1rem, 3vw, 2rem); /* Adjusts between 1rem and 2rem based on viewport width */
}

@media (max-width: 768px) {
  .grid-container {
    gap: 1rem; /* Smaller spacing for smaller screens */
  }
}

Comparing gap and Margins

Feature gap Margins
Where It’s Applied Directly to the container On individual grid items
Edge Handling No extra space at edges May require fixes for edges
Ease of Use One property does it all Needs multiple selectors
Performance Optimized by browsers Can involve more calculations
Responsive Design Adapts naturally Often needs extra rules

Why Use gap?

Using gap reduces complexity. No need for negative margins, extra wrappers, or extra selectors. This streamlines your code and helps browsers handle layouts more efficiently.

Next, we’ll dive into advanced grid layout techniques to take your designs even further.

8. Nested Grid Structures

Nested grids take your layout designs to the next level by allowing grid items to act as their own grid containers. This approach helps you create detailed and well-organized layouts.

Basic Nested Grid Setup

To create a nested grid, set display: grid on a grid item. Here’s a quick example:

.parent-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
}

.nested-grid-item {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
}

How Nested Grids Work

Nested grids function independently from their parent grid. This means that track sizes, grid lines, and gaps aren’t passed down. You’ll need to define alignment and spacing within each nested grid separately.

Using Subgrid for Shared Tracks

If you want a nested grid to inherit the parent’s track definitions, use the subgrid feature. Here’s how:

.parent-grid {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    gap: 32px;
}

.nested-grid {
    display: grid;
    grid-template-columns: subgrid;
    /* Inherits column definitions from the parent */
}

Managing Spacing and Alignment

To maintain consistent spacing, you can follow an 8-point grid system. Here’s an example:

.nested-grid {
    display: grid;
    gap: 16px;
    padding: 24px;
    justify-items: start;
    align-items: center;
}

This method ensures clean and predictable layouts across different screen sizes.

Browser Compatibility

CSS Grid and nested grids are supported in most modern browsers. However, the subgrid feature is relatively new and may not work in older browser versions. Be sure to include fallbacks for broader compatibility.

“The real difference between using Flexbox and CSS Grid is in the amount of code: The code for creating a complex layout in Flexbox is more complex, dispersed and time-consuming, while that created with the Grid is much faster, tidier and simpler.”

9. Grid Item Flow Control

Controlling how grid items flow is essential for creating flexible and efficient layouts. Building on nested grids, managing item flow allows for even more precise layout control.

Understanding Flow Direction

By default, grid items are placed in rows, filling one row before moving to the next. Here’s an example:

.grid-container {
  display: grid;
  grid-template-columns: repeat(8, 50px);
  grid-auto-flow: row;
}

To create vertical layouts, you can switch to a column flow like this:

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  grid-template-rows: 50px 50px 50px;
  grid-auto-flow: column;
}

Making the Most of Space

The dense packing algorithm helps fill gaps by rearranging smaller items into available spaces:

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-auto-flow: dense;
  gap: 16px;
}

Accessibility Considerations

“The dense keyword makes auto-placement algorithm to reorder items in order to back-fill holes in the layout.” – CSS-Tricks

When choosing a flow type, consider both design needs and accessibility:

Flow Type Ideal Use Case Accessibility Notes
row Text-heavy content, forms, and sequential information Keeps source order intact
column Vertical designs like sidebars Maintains source order
dense Image grids, card layouts, and decorative elements May disrupt source order, so use with caution

Pairing with Auto-Placement

Combining flow control with auto-placement gives you even more flexibility. For example:

.adaptive-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  grid-auto-flow: row;
  grid-auto-rows: minmax(100px, auto);
  gap: 24px;
}

This setup creates a responsive grid that adjusts to the viewport, automatically generating rows with a minimum height of 100px.

Browser Support

Since March 2017, most modern browsers have offered native support for CSS Grid without prefixes. Always test your layouts across browsers to ensure they behave as expected.

10. Building Screen Reader-Friendly Grids

When designing grid layouts, it’s crucial to ensure they are accessible to everyone, including users relying on screen readers. The key lies in maintaining a logical source order that screen readers can easily follow.

Keeping a Logical Source Order

Use CSS Grid to control the visual layout, but avoid altering the source order with it:

.accessible-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

Balancing Visual and Logical Order

Property Usage Accessibility Impact Recommendation
Visual-only adjustments Maintains source order Safe to use
Logical reordering Disrupts screen reader flow Avoid
Grid template areas Use for visual layout only Test thoroughly

“Authors must use order and the grid-placement properties only for visual, not logical, reordering of content. Style sheets that use these features to perform logical reordering are non-conforming.” – W3C’s CSS Grid docs

Preserving Semantic Structure

To maintain proper semantics, consider nested grids or display: contents:

.semantic-grid {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

.nested-content {
  display: contents; /* Keeps semantic structure intact */
}

Always test these methods with assistive tools to ensure they work as intended.

Testing for Grid Accessibility

  • Keyboard navigation: Ensure the tab order follows a logical sequence.
  • Screen reader testing: Listen to the content to catch any issues.
  • Source order checks: Verify the HTML structure matches the reading flow.
  • Semantic validation: Confirm proper heading levels and ARIA attributes.

Designing with Mobile-First in Mind

A mobile-first approach ensures content order is prioritized:

.responsive-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

@media (min-width: 768px) {
  .responsive-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

Remember, CSS Grid’s visual adjustments don’t change how screen readers interpret the content.

“If the visual order and the DOM order don’t match, it can irritate and confuse users up to a point where the experience is so bad that the site is unusable.” – Manuel Matuzovic

Conclusion

CSS Grid has transformed web layout design, offering flexible solutions that meet modern web development needs while preparing for future challenges.

Performance Advantages

Using CSS Grid can lead to better performance by simplifying the DOM and optimizing how layouts are processed:

Advantage Effect How to Apply
Faster Loading Times Fewer nested elements Use grid-template-areas
Smoother Rendering Reduced reflows and repaints Create layouts with single rule sets
Better User Experience Improved responsiveness Utilize minmax() and fr units
Cleaner Code for SEO Simplified structure Combine semantic HTML with grid areas

Example Integration

Here’s a practical example of how to set up a responsive and scalable grid layout:

.main-layout {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1rem;
    container-type: inline-size;
}

This approach ensures your design is adaptable and maintains consistency across different screen sizes.

Preparing for the Future

To ensure your layouts remain effective and accessible in the long run:

  • Use semantic HTML to maintain structure while styling visually.
  • Pair CSS Grid with critical CSS for faster loading.
  • Test your layouts across multiple browsers.
  • Address accessibility concerns to make designs inclusive.

CSS Grid combines simplicity and power, making it an essential tool for creating clean, efficient, and adaptable web layouts.

Put Your CSS Skills into Action! 🚀

Reading about CSS is great, but real growth comes from practice! Head over to PlayCSS.app and start tackling real-life UI challenges today. Build, learn, and level up your frontend skills!

Our site uses cookies. By using this site, you agree to the Privacy Policy and Terms of Use.