Used in graphic design to guide objects.
In this unit, we will delve into the core of the CSS Grid Layout: defining and working with rows and columns. This is the foundation upon which all grid-based designs are built.
The first step in creating a grid layout is defining the grid itself. This is done using the grid-template-rows
and grid-template-columns
properties. These properties allow you to specify the number and sizes of the rows and columns in your grid.
For example, if you wanted to create a grid with three columns of equal width, you would write:
.container { display: grid; grid-template-columns: 1fr 1fr 1fr; }
In this example, 1fr
is a flexible length unit, which represents a fraction of the free space in the grid container.
fr
UnitThe fr
unit is a flexible length that represents a fraction of the remaining space in the grid container. This unit allows you to create flexible grids that adapt to the size of their container.
For example, if you wanted to create a grid with two columns, where the first column is twice as wide as the second, you would write:
.container { display: grid; grid-template-columns: 2fr 1fr; }
In this example, the first column will always be twice as wide as the second, regardless of the size of the grid container.
grid-auto-rows
and grid-auto-columns
PropertiesIn addition to grid-template-rows
and grid-template-columns
, CSS Grid also provides the grid-auto-rows
and grid-auto-columns
properties. These properties are used to specify the size of any rows or columns that are created implicitly.
For example, if you have more grid items than cells in your grid, CSS Grid will automatically create new rows or columns to accommodate these items. The grid-auto-rows
and grid-auto-columns
properties allow you to control the size of these implicitly created rows and columns.
.container { display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 100px; }
In this example, any new rows that are created will have a height of 100px.
By understanding and effectively using these properties, you can create complex grid layouts that are both flexible and robust. In the next unit, we will explore how to control the spacing between grid items using the grid-gap
property.