CSS Grid
CSS Grid Layout introduces a two-dimensional grid system to CSS. Grids can be used to lay out major page areas or small user interface elements. A grid is an intersecting set of horizontal and vertical lines – one set defining columns, and the other, rows. Elements can be placed onto the grid, within these column and row lines.
Grid rows and columns
grid-template-rows
and grid-template-columns
define the structure of a grid by defining columns and rows
grid-template-columns: 50px 50px
grid-template-rows: 50px 50px
grid-template-columns: 50px 50px 50px
Grid units
You can use absolute and relative units like px
and em
in CSS Grid
to define the size of rows and columns. You can use these as well:
fr
: sets the column or row to a fraction of the available space
auto
: sets the column or row to the width or height of its content automatically,
%
: adjusts the column or row to the percent width of its container.
grid-template-columns: auto 50px 10% 2fr 1fr
grid-template-rows: 3ch auto minmax(10px, 60px)
Gaps
To add a gap between the columns, use the column-gap
,
row-gap
, or gap
for short.
column-gap: 10px
row-gap: 20px;
gap: 50px 5px;
Spacing
To specify grid item's size and location use grid-column
and grid-row
Second item:
grid-column: 2 / 4
Third item:
grid-row: 1 / 3
Alignment
To align grid items horizontally use justify-items
and justify-self
.
To align grid items vertically use align-items
and align-self
.
justify-items: center
align-items: start
Gird areas
The grid-template-areas
CSS property specifies named grid areas,
establishing the cells in the grid and assigning them names. The grid-area
can then be used to assign grid items to these areas.
grid-template-areas:
"a a a"
"b c c"
"b c c";
Fourth item:
grid-area: 2 / 1 / 4 / 3
Repeat and Minmax functions
Reduce repetition using the repeat
function. minmax
function can
be used to dynamically set grid items size in grid-template-columns
and
grid-template-rows
.
grid-template-columns: repeat(2, 1fr 50px) 20px
grid-template-columns: 100px minmax(300px, 100%)
grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(60px, 1fr));