OneBite.Dev - Coding blog in a bite size

use css grid

Code snippet for how to use css grid with sample and detail explanation

CSS Grid is an efficient and flexible method of designing and organizing layouts on the web. It makes it easier to design complex web layouts without relying heavily on hacks or tricks.

Code snippet: Basic CSS Grid Structure

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

.grid-item {
  border: 1px solid black;
  padding: 20px;
}

In this code snippet, we denote a basic CSS Grid structure with three equal width columns and each grid cell having a 10px gap between them.

Code Explanation for Basic CSS Grid Structure

The mentioned CSS code can be dissected into several parts, each with its unique purpose and functionality.

The display property set to grid indicates that a container is to function as a grid container. Upon declaration, its immediate children become grid items. In our code snippet, the parent container with the class mark .display-grid adopts the property display: grid.

The grid-template-columns property is responsible for the horizontal layout of the grid. It specifies the width or fraction (fr) of each column within the grid. In our case, grid-template-columns: repeat(3, 1fr) determines that the grid will have three columns of equal width with the 1fr signifying an equal share of available space.

Gap property sets the gutter size between rows and columns of a grid. Thus, gap: 10px introduces 10px spacing between each grid cell.

The .grid-item is a generic class for each grid item. Here, each item gets a solid black border of 1px and 20px padding inside.

This sets the way for a flexible, dynamic grid layout that ensures all items line up in a neat and tidy manner, irrespective of the content inside them. As a result, managing complex web layouts becomes much simpler.

css