DEV Community

Cover image for Learn CSS Grid: Simple Guide with Plenty of Examples
Eleftheria Batsou
Eleftheria Batsou

Posted on • Originally published at eleftheriabatsou.hashnode.dev on

Learn CSS Grid: Simple Guide with Plenty of Examples

Hey there! If you've ever felt like CSS Grid is a bit like trying to solve a Rubik's Cube blindfolded, you're not alone. I'm Eleftheria, and today, I'm here to help you navigate CSS grid with ease. Let's dive in. 🤿

Introduction to CSS Grid

CSS Grid is made to allow you to create complex, two-dimensional layouts that were previously quite a headache to achieve. Before Grid, we were juggling with floats, tables, or flexbox for layouts. Grid came along and said, "Hold my beer," offering a more intuitive and powerful way to structure web pages.

Why Learn CSS Grid?

  • Efficiency : Grid simplifies the way you design layouts, reducing the need for nested elements just for layout purposes.

  • Flexibility : It's fantastic for responsive design, adapting beautifully to different screen sizes.

  • Power : With Grid, you can align elements both vertically and horizontally with ease, which was a nightmare with older methods.

The Basics of CSS Grid

Let's start at the very beginning. To use CSS Grid, you need to define a container as a grid. For example:

.container { display: grid;}
Enter fullscreen mode Exit fullscreen mode

This simple line turns the .container into a grid container, which means its direct children will become grid items.

Creating Grid Columns and Rows

You define grid structure by specifying columns and rows:

.grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr; /* Three columns with equal width */
    grid-template-rows: auto auto auto;  /* Three rows with automatic height */
}

Enter fullscreen mode Exit fullscreen mode

Here, 1fr means one fraction of the available space, making columns equal in width.

Placing Items in the Grid

You can place items in specific areas using grid-column and grid-row properties:

.item-a {
    grid-column: 1 / 3; /* Start at line 1, end at line 3 */
    grid-row: 1 / 2;    /* Span from line 1 to line 2 */
}

Enter fullscreen mode Exit fullscreen mode

This places .item-a starting from the first column line to the third, and through the first row.

Grid Lines and Areas

You can name lines for easier reference:

.grid-container {
    grid-template-columns: [start] 1fr [line2] 1fr [end];
    grid-template-rows: [row1-start] auto [row2-start] auto [row3-end];
}
Enter fullscreen mode Exit fullscreen mode

Then use these names:

.item-b {
    grid-column: start / line2;
    grid-row: row1-start / row2-start;
}
Enter fullscreen mode Exit fullscreen mode

Grid Areas

For a more visual approach, you can name areas:

.grid-container {
    display: grid;
    grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
}
Enter fullscreen mode Exit fullscreen mode

Then assign elements to these areas:

<div class="grid-container">
    <div class="header">Header</div>
    <div class="sidebar">Sidebar</div>
    <div class="main">Main</div>
    <div class="footer">Footer</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Enter fullscreen mode Exit fullscreen mode

More Examples of CSS Grid in Action

1. Responsive Layout with Media Queries

One of the strengths of CSS Grid is its ease in handling responsive designs. Here's an example that shows how to adjust grid layouts for different screen sizes :

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

@media (max-width: 768px) {
    .grid-container {
        grid-template-columns: 1fr;
    }
}
Enter fullscreen mode Exit fullscreen mode

This setup creates a grid where each item is at least 300px wide but grows to take up available space. On screens smaller than 768px, it shifts to a single column layout.

2. Complex Layout: Magazine Style

Imagine a magazine page with a large featured article, smaller side articles, and ads:

<div class="grid-container">
    <article class="featured">Featured Article</article>
    <article class="side">Side Article 1</article>
    <article class="side">Side Article 2</article>
    <div class="ad">Advertisement</div>
    <footer class="footer">Footer</footer>
</div>
Enter fullscreen mode Exit fullscreen mode
.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-areas: 
        "featured featured ad"
        "side1 side2 ad"
        "footer footer footer";
    gap: 10px;
}

.featured { grid-area: featured; }
.side:nth-child(1) { grid-area: side1; }
.side:nth-child(2) { grid-area: side2; }
.ad { grid-area: ad; }
.footer { grid-area: footer; }
Enter fullscreen mode Exit fullscreen mode

This example uses named grid areas to create a complex, but visually appealing layout.

3. Nested Grids for Component Design

For components within your grid, you might nest grids:

<div class="grid-container">
    <div class="card">
        <h2 class="card-title">Card Title</h2>
        <div class="card-content">
            <p>Content Here</p>
            <button class="card-button">Action</button>
        </div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 20px;
}

.card {
    display: grid;
    grid-template-columns: 1fr;
    gap: 10px;
}

.card-title {
    /* Styles for title */
}

.card-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 10px;
}

.card-button {
    align-self: flex-start;
}
Enter fullscreen mode Exit fullscreen mode

Here, each card itself uses a grid to layout its title and content, demonstrating how grids can be nested for fine control over design elements.

4. Dynamic Grid with Images

For a gallery or portfolio:

<div class="gallery">
    <img src="img1.jpg" alt="Image 1">
    <img src="img2.jpg" alt="Image 2">
    <img src="img3.jpg" alt="Image 3">
    <!-- More images -->
</div>
Enter fullscreen mode Exit fullscreen mode
.gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 10px;
}

.gallery img {
    width: 100%;
    height: auto;
}
Enter fullscreen mode Exit fullscreen mode

This grid dynamically adjusts to fill the container with images, each at least 200px wide, fitting as many as possible into each row.

Advanced Grid Features

  • Grid Auto-Flow : Automatically places items.

  • Grid Gaps : Adds space between grid cells.

  • Minmax(): Defines a size range for rows or columns.

Grid Auto-Flow

Grid Auto-Flow controls how the browser should fill in the grid with items when they are not explicitly placed. By default, items are placed in row-major order, which means items fill across rows before moving to the next row. However, you can change this behavior:

  • row : The default behavior where items are placed in rows before moving to the next column.

  • column : Items are placed in columns before moving to the next row.

  • dense : This option tells the browser to fill in gaps in the grid as items are placed, potentially rearranging items to avoid empty spaces. This can result in an "optimal" arrangement but can also lead to unexpected layouts if not used carefully.

Example:

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-auto-flow: column; /* Items will fill by column before moving to next row */
}
Enter fullscreen mode Exit fullscreen mode

Grid Gaps (or Gutter)

Grid Gaps add space between grid cells, which is crucial for visual breathing room in your layout. You can set gaps for rows, columns, or both:

Example:

.grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 20px 40px; /* 20px vertical gap, 40px horizontal gap */
    grid-row-gap: 30px; /* Alternative for vertical gap */
    grid-column-gap: 50px; /* Alternative for horizontal gap */
}
Enter fullscreen mode Exit fullscreen mode

Using gap is shorthand for both grid-row-gap and grid-column-gap. This feature helps in creating a more polished and organized look, making your content feel less cramped.

Minmax() Function

The Minmax() function in CSS Grid allows you to define a size range for grid tracks (rows or columns). This is extremely useful for creating flexible yet controlled layouts:

Example:

.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
}
Enter fullscreen mode Exit fullscreen mode
  • minmax(min, max): Here, min is the minimum width (or height for rows) the track can take, and max is the maximum. The track will grow from min to max as more space becomes available.

  • auto-fill inside repeat alongside minmax means the browser will automatically generate as many columns as fit within the container, each having a minimum width of 100px but can expand if there's space.

  • 1fr means the track can grow to take up an equal fraction of the available space if there's room after all minimum sizes are accounted for.

Real Example Use:

Imagine designing a dashboard where you want cards to have at least 200px width but grow to fill the space without exceeding 400px:

Solution:

.dashboard {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 400px));
    gap: 20px;
}
Enter fullscreen mode Exit fullscreen mode

This setup ensures each card is visible and usable on smaller screens while maximizing space on larger displays.

  • Grid Auto-flow helps in managing how items are naturally placed within your grid, optimizing for space or maintaining order.

  • Grid Gaps provide the breathing room that makes layouts more visually appealing and user-friendly.

  • Minmax offers the flexibility to design layouts that adapt beautifully to different screen sizes and content volumes.

Conclusion

I hope by now, you've seen Grid not just as a layout tool, but as a creative companion in your web design adventures. CSS Grid has transformed how we approach layout design, offering a blend of simplicity and power that was hard to imagine before its arrival.

Remember, mastering Grid isn't about memorizing every property or function, but understanding its logic. Like learning any new language, it's about practicetrying out different configurations, seeing how elements respond, and adapting your design to the fluidity of the web.

As you incorporate Grid into your projects, whether they're personal blogs, complex dashboards, or innovative web applications, you'll find yourself equipped to handle challenges with elegance and efficiency. Keep this guide handy, refer back to these examples, and most importantly, keep experimenting.

Thank you for joining me on this exploration of CSS Grid.


👋 Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.

🥰 If you liked this article, consider sharing it.

🔗 All links | X | LinkedIn

Top comments (0)