CSS Grid in Action - Setting Up Your First Grid Container

2023-10-11
By: O. Wolfson

Introduction

Having decoded the basic terminology of CSS Grid in our last post, it's time to roll up our sleeves and dive into the practical side of things. This section will guide you through the initial steps of setting up a grid container, introducing you to columns, rows, and the magical fr unit. Ready to see some magic? Let's dive in!


1. Creating a Grid Container

The first step to working with Grid is defining a container. This is done by setting an element's display property to grid.

css
.container {
  display: grid;
}

By doing this, you've transformed your container element into a canvas where you can start defining rows, columns, and placing items.


2. Defining Columns and Rows

The backbone of any grid layout lies in its rows and columns. With CSS Grid, this is achieved using the grid-template-columns and grid-template-rows properties.

css
.container {
  display: grid;
  grid-template-columns: 200px 200px 200px;
  grid-template-rows: 150px 150px;
}

This setup gives you a grid of 3 columns, each 200 pixels wide, and 2 rows, each 150 pixels tall.


3. Embracing the fr Unit

While pixel values are clear and straightforward, CSS Grid introduced a flexible unit called fr, short for fraction. This unit represents a fraction of the available space, making your grid responsive to its container's size.

css
.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
}

Here, the middle column will be twice as wide as the other two. If the container is 900 pixels wide, the columns will be 300px, 600px, and 300px wide respectively.


4. A Practical Example

To truly appreciate the ease and power of setting up a grid container, let’s look at a practical example:

html
<div class="container">
  <div class="item">A</div>
  <div class="item">B</div>
  <div class="item">C</div>
  <div class="item">D</div>
  <div class="item">E</div>
</div>
css
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}
.item {
  background-color: #ddd;
  padding: 20px;
  text-align: center;
}

This will create a neat grid of items A to E, with three items on the first row and two on the second, thanks to our 3-column setup.


Conclusion

Setting up a grid container is the foundation of creating powerful, flexible, and responsive designs with CSS Grid. By understanding columns, rows, and the fr unit, you can begin crafting intricate layouts with ease.

Coming Next: In our subsequent post, we'll dive into positioning grid items, taking our grid layouts to the next level. Stay tuned!