Refining our Grid System | Layout with CSS Grid

Building on the Basics

We’ve already covered the fundamental concepts of CSS Grid Layout. Let’s delve deeper into some advanced techniques and best practices:

1. Responsive Grids

  • Media Queries: Use media queries to adjust grid properties based on screen size.
  • Flexible Grid Tracks: Use fr units for grid tracks to create flexible layouts that adapt to different screen sizes.

Example:

CSS

.container {

  display: grid;

  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

}

2. Nested Grids

  • Create nested grids within grid containers for more complex layouts.

Example:

HTML

<div class=”container”>

  <div class=”header”>Header</div>

  <div class=”main”>

    <div class=”item”>Item 1</div>

    <div class=”item”>Item 2</div>

  </div>

  <div class=”footer”>Footer</div>

</div>

CSS

.container {

  display: grid;

  grid-template-rows: 100px 1fr 100px;

}

.main {

  display: grid;

  grid-template-columns: 1fr 1fr;

}

3. Grid Templates

  • Use grid-template-areas to define named grid areas and place items within them.

Example:

CSS

.container {

  display: grid;

  grid-template-columns: 1fr 1fr 1fr;

  grid-template-rows: 100px 1fr;

  grid-template-areas:

    “header header header”

    “main main sidebar”;

}

.header {

  grid-area: header;

}

.main {

  grid-area: main;

}

.sidebar {

  grid-area: sidebar;

}

4. Grid Gaps

  • Use grid-gap to control the spacing between grid items.

Example:

CSS

.container {

  display: grid;

  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

  grid-gap: 20px;

}

5. Grid Auto-Placement

  • Use grid-auto-flow to control how items are placed in the grid.

Example:

CSS

.container {

  display: grid;

  grid-auto-flow: column dense;

} You can create complex and responsive layouts using CSS Grid by mastering these techniques. Experiment with different combinations and find the best approach for your specific needs.

Basic Grid syntax | Layout with CSS Grid
Placing and sizing Grid Layout items | Layout with CSS Grid

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?