CSS Grid Layout Examples | Basic Setup & Responsive Design

Photo of author
Written By Charlie Giles

Devoted WordPress fan behind CodeCraftWP. Sharing years of web expertise to empower your WordPress journey!

Disclosure: This post may contain affiliate links, which means if you click on a link and make a purchase, I may earn a commission at no additional cost to you.

Discover how to use CSS Grid Layout in your projects with examples of basic setup, justification, auto columns, fixed rows and columns, spanning items, multi-track grids, and responsive designs. Ideal for web developers looking to enhance their layout skills.

Basic Grid Setup

Defining Grid Container

Imagine you’re planning a party and need to arrange chairs in rows for your guests. Before you can place any chairs, you first need to define the space where they will be seated—let’s call this area your “grid container.” In CSS Grid, we use the display: grid; property on a parent element (which could be anything from a div to an article) to create this container. This is like setting up the room for your party.

Creating Grid Items

Once you’ve defined the grid container, it’s time to bring in the guests—your “grid items.” These are the individual cells that make up the grid layout. You can think of each item as a chair that needs to be placed into one of the rows and columns you’ve created. In CSS Grid, we use the grid-template-columns and grid-template-rows properties to define the number and size of these rows and columns.

For example, if you want to have three chairs in every row and four rows for your guests, you would write:
css
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(4, auto);
}

This setup creates a grid with 12 cells (3 columns by 4 rows), each designed to hold one guest. Each chair will now be neatly arranged in its designated spot—no more awkwardly spaced chairs or guests left standing!


Justified Alignment

Horizontal Justification

Imagine you’re arranging books on a shelf. You want them to line up perfectly so that the edges create a straight and clean look. That’s what horizontal justification does for your grid layout—aligning items edge-to-edge to make a seamless, cohesive design. In CSS Grid, this is achieved using the justify-items property at the container level or by setting individual item properties like justify-self.

When you apply horizontal justification, each row in your grid adjusts its columns to ensure all items are aligned along their left and right edges. Think of it as ensuring that every book on your shelf is perfectly lined up so that no matter how many books you have, they form a neat and tidy line.

Vertical Justification

Vertical justification works much like its horizontal counterpart but operates in the opposite direction. Instead of aligning items along their left and right edges, vertical justification ensures that grid items are aligned at their top and bottom edges to create a visually appealing layout. This is controlled via the align-items property for the container or by using align-self on individual items.

Consider a scenario where you’re stacking books vertically in columns; you want each column of books to be perfectly centered and aligned so that the stacks look balanced from top to bottom, not just side to side. This is exactly what vertical justification does—ensures your grid items are neatly stacked, creating a harmonious and organized display.

By mastering both horizontal and vertical justification, you can create grids that are not only aesthetically pleasing but also user-friendly, ensuring that content is easy to read and navigate on various devices and screen sizes.


Auto Columns

Automatically Sizing Columns

Imagine you’re arranging a set of books on a shelf. You don’t want them all to be exactly the same size; instead, you might want some to take up more space while others fit snugly in between. That’s where auto-columns come into play in CSS Grid.

When you use auto for column sizes, each grid item will automatically adjust its width based on the available space and its own content. This is akin to fitting puzzle pieces together—each piece (or grid item) finds its perfect spot without overcrowding or leaving too much empty space.

Flexible Column Widths

Think of flexible column widths as a series of elastic bands stretching across your grid area, allowing items to grow and shrink based on the available space. With fr units in CSS Grid, you can define columns that fill up the remaining space proportionally. For example:

markdown
| Column 1 (2fr) | Column 2 (1fr) |

In this setup, if there’s a lot of content in Column 1, it will take up twice as much space as Column 2. This is especially useful for creating responsive layouts that adapt to different screen sizes.

When you use auto and flexible widths together, you create a grid that can dynamically adjust to the user’s needs—like an adaptive playlist that reshuffles songs based on your mood!


Fixed Rows and Columns

Specifying Row Size

When setting up a grid layout using CSS Grid, one of the key elements to consider is the row size. Think of rows like the floors in a building—each floor has its own designated space for different rooms or amenities. In the context of a grid, specifying the row size is akin to defining how many stories your building will have and what each story can accommodate.

To define the row size, you can use several properties such as grid-template-rows. This property allows you to set up multiple rows with various heights, making it possible to create a layout that perfectly fits your design needs. For example, if you’re designing a website for an e-commerce platform, you might want to allocate more space for images and less for text in the product listings.

css
.grid-container {
display: grid;
grid-template-rows: 50px auto; // This sets one row with a fixed height of 50 pixels and another that will grow based on content.
}

Defining Column Dimensions

Just as defining rows is crucial, so too are column dimensions. Columns in CSS Grid act like the columns in a building—they support the structure and create distinct areas for different purposes. In web design, this means creating separate sections for navigation, content, and more.

Defining column dimensions involves using properties such as grid-template-columns. This property allows you to specify how wide each column should be, either with fixed values or by using flexible units like fr (fraction). For instance, if you want the first two columns to be larger than the others because they contain important content, you can do so.

css
.grid-container {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); // This creates three equal-width columns.
}

By carefully defining both row and column sizes, you ensure that your grid layout is not only visually appealing but also functional. Imagine a building where each floor has been meticulously designed to accommodate specific activities; similarly, a well-defined grid ensures every element on the webpage serves its purpose seamlessly.


Spanning Items

Row Span Example

Imagine you’re laying out a table at a restaurant. You want to place a large serving dish that can span across multiple seats, allowing everyone to see and reach for it. In CSS Grid, this is exactly what the row-span property does. It allows an item to take up more than one row in a grid container. For instance, if you have a 3×3 grid and want to place a large image that spans two rows, you would use:

css
.item {
grid-row: span 2;
}

Column Span Example

Now, think of it like the opposite scenario—placing a tall columnar plant in your living room. You might want this plant to stretch up and take over an entire row of shelves. In CSS Grid, column-span works similarly but for columns instead of rows. If you have a 3×3 grid and wish to place a vertical banner that spans two columns, the code would look like:

css
.item {
grid-column: span 2;
}

These properties allow items in your grid layout to break free from their usual confines, creating dynamic and flexible designs that can adapt to various screen sizes and content needs.


Multi-Track Grid

Creating Multiple Tracks

Imagine you’re planning a grand garden party, where each type of plant has its own special spot. In web design, creating multiple tracks in a grid is like organizing your garden into distinct areas for different flowers or plants. Each track can represent a unique row that houses specific types of content.

To create multiple tracks, you use the grid-template-columns and grid-template-rows properties. These properties allow you to define how many columns or rows you need, much like deciding on how many flower beds you want in your garden. For instance, if you wanted three main sections for flowers, vegetables, and herbs, you might write something like this:

css
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* Three columns with different sizes */
}

Specifying Track Names

Now that we’ve created our garden beds (tracks), let’s give each one a unique name for easy identification. In CSS Grid, this is done using the grid-track shorthand property. By naming your tracks, you can easily refer to them in your grid template or use them as targets for layout purposes.

For example, if we named our three sections “flowers”, “vegetables”, and “herbs”, we could write:

css
.grid-container {
display: grid;
grid-template-columns: 1fr vegetables 1fr; /* Named track 'vegetables' */
}

This way, you can use the name in your HTML like this:

“`html

Flowers
Vegetables
Herbs

“`

By specifying track names, you not only make your code more readable and maintainable but also open up possibilities for dynamic grid layouts that can adapt based on the content or context.


Responsive Design

Media Queries in CSS Grid

When crafting a website that needs to look perfect on every device, from smartphones to large desktop monitors, media queries become your best friend. They act like a smart detective, automatically adjusting the layout based on the screen size and orientation of the user’s device. Think of them as little magicians who can transform your grid into different shapes depending on where it’s being viewed—from a cozy tablet in a coffee shop to an expansive desktop monitor at home.

Flexible Grid Layouts

Flexible grid layouts are like giving your website a pair of adjustable glasses that adapt to the viewer’s needs. Imagine you have a photo album; instead of showing all photos in one row, each one gets its own space, but when the screen is narrower, they stack vertically into a single column. This ensures every picture (or element) has enough breathing room no matter how small or large the device.

In CSS Grid, these layouts are achieved through properties like grid-template-columns and grid-auto-rows, which automatically adjust based on the available space. It’s like having a magical wardrobe that expands to fit all your clothes perfectly, whether you’re packing for a day trip or a week-long vacation.

Leave a Comment