CSS Grid: An Ultimate Guide
In this article, we will learn about css grid and its uses in today's web development.
What is CSS GRID?
CSS Grid is a fundamentally new approach to building layouts using CSS.
CSS Grid is a set of CSS properties for building 2-dimensional layouts
The main idea behind CSS Grid is that we divide a container element into
rows and columns that can be filled with its child elements
In two-dimensional contexts, CSS Grid allows us to write less nested HTML
and easier-to-read CSS
CSS Grid is not meant to replace flexbox! Instead, they work perfectly
together. Need a 1D layout? Use flexbox. Need a 2D layout? Use CSS Grid.
Grid Container:
display
Defines the element as a grid container and establishes a new grid formatting context for its contents.
.container {
display: grid;
}
grid-template-columns and grid-template-rows:
To establish the grid row and column tracks. One length unit for each track. Any unit can be used, new fr fills unused space
row-gap,column-gap and gap
To create empty space between tracks
.container {
gap: 20px;
}
justify-items:
To align items inside rows / columns (horizontally)
.container {
justify-items: start | end | center | stretch;
}
align-items
To align items inside rows / columns (vertically)
.container {
align-items: start | end | center | stretch;
}
justify-content and align-content:
To align entire grid inside grid container. Only applies if
container is larger than the grid
.container {
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
Grid Items(Children):
grid-column and grid-row
To place a grid item into a specific cell, based on line numbers. span keyword can be used to span an item across more cells
.item {
grid-column: <start-line> / <end-line> | <start-line> / span <value>;
grid-row: <start-line> / <end-line> | <start-line> / span <value>;
}
justify-self and align-self:
To overwrite justify-items / align-items for single items