Skip to main content

Understanding CSS Grid in CSS Positioning (Live Playground)

CSS Grid is a modern layout module that provides an efficient way to create two-dimensional grid-based layouts. In this tutorial, you will learn about the CSS Grid layout module, its properties, and how to use them to create flexible and responsive grid-based layouts, along with sample code and simple explanations.

Grid container

To create a grid container, set the display property of an element to grid or inline-grid. This allows you to control the layout of its child elements using Grid properties.

Example:

CSS
.grid-container {
display: grid;
}
HTML
<div class="grid-container">
<div>Child 1</div>
<div>Child 2</div>
<div>Child 3</div>
</div>

In this example, a grid container is created, and its child elements are arranged in a grid by default.

Live Playground, Try it Yourself

Grid columns and rows

The grid-template-columns and grid-template-rows properties define the size and number of columns and rows in the grid.

Example:

CSS
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 100px);
}

In this example, the grid container has 3 columns of equal width and 2 rows of 100px height.

Live Playground, Try it Yourself

Grid gap

The gap, row-gap, and column-gap properties are used to set the spacing between grid items.

Example:

CSS
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}

In this example, the gap property is set to 10px, creating a 10px gap between grid items both horizontally and vertically.

Live Playground, Try it Yourself

Grid items

Grid items are the direct children of grid containers. You can control their position and size using grid item properties like grid-column, grid-row, grid-area, and align-self.

Example:

CSS
.grid-item {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
HTML
<div class="grid-container">
<div class="grid-item">Child 1</div>
<div>Child 2</div>
<div>Child 3</div>
</div>

In this example, the grid-column and grid-row properties are used to position and size the first grid item.

Live Playground, Try it Yourself

Conclusion

By understanding the CSS Grid layout module and its properties, you can create flexible and responsive grid-based layouts for your web pages with ease. CSS Grid offers a more powerful and modern approach to positioning elements, making it an excellent addition to your CSS toolkit.