tutorials/css/the complete guide/14. using_css_grid.md

2.2 KiB

Using The CSS Grid

Creating highly customizable page layouts.

What Is The CSS Grid

It allows you to define a grid of rows and columns, and to specify which element should be positioned where.

The basic HTML setup we'll use throughout this module:

<div class="container">
    <div class="el1">Element 1</div>
    <div class="el2">Element 2</div>
    <div class="el3">Element 3</div>
    <div class="el4">Element 4</div>
</div>

Turning A Container Into A CSS Grid

We can turn a container element into a grid by setting display: grid;.

Defining Columns And Rows

We can use the property grid-template-columns on the grid container to define the width of the columns (not the number of columns). e.g. grid-template-columns: 200px 150px 20%; would mean, first column is 200px wide, second is 150px wide, and the third is 20% of the container's width.

Another unit we can use in the grid-template-columns is fr (fraction), it splits the remaining space between the columns using the fraction number. e.g. grid-template-columns: 200px 2fr 20% 1fr; would split the remaining space between second and fourth columns 2:1 repectively.

Likewise, we can use the grid-template-rows property to set the height or number of rows. e.g. grid-template-rows: 5rem 2.5rem; would set the number of rows to 2, and their height 5rem and 2.5rem respectively.

Note: We can still add more rows to the grid but we explicitly defined sizes for first 2 rows only.

Positioning Child Elements In A Grid

Using the grid-column-start and grid-column-end properties, we can span a single cell over multiple columns, or define the place inside the grid for this child element. e.g. grid-column-start: 3; grid-column-end: 5; make the child element to start at line 3, and span horizontally till line 5.

Likewise, we also have grid-row-start and grid-row-end properties for placement and spanning of a child element using rows.

Keep in mind that the numeric value you use for these properties is the line number. e.g. the following table (grid) has 4 lines for columns, starting from 1 to 4, and 4 for rows.

a b c
d e f
g h i

Using element-sizing, repeat And minmax