Creating Complex Layouts with CSS Grid
With the Grid layout, you can divide a web page into multiple sections similar to a chess board.
However, when you look at actual websites, you'll notice that some sections are larger than others.
Not all sections are uniformly aligned.
To achieve such complex layouts, you need to use additional Grid features.
Utilizing Grid Properties
You can make your Grid layouts more efficient by utilizing the following properties.
grid-gap
Defines the spacing between grid items.
.container { grid-gap: 10px; /* Set the gap between grid items to 10px */ }
grid-auto-rows, grid-auto-columns
Specify the size of rows or columns that are not explicitly defined.
.container { grid-auto-rows: 100px; /* Set the row size to 100px */ grid-auto-columns: 200px; /* Set the column size to 200px */ }
fr Unit
The fr
unit is used in CSS Grid layout as a length unit
for dividing available space within the Grid Container.
fr
stands for Fraction
, representing a fraction of the allocated space to the grid track.
For instance, you can use the fr
unit on columns or rows in a CSS grid layout:
.container { display: grid; /* Establish a grid container */ grid-template-columns: 1fr 2fr 1fr; /* Create 3 columns, the middle column is twice as wide as the side columns */ }
In this example, the grid container consists of three columns, with the middle column being twice as wide as the side columns.
1fr
represents one portion of available space, and 2fr
stands for two portions of available space.
Thus, the total space is divided into 4 parts, with the middle column occupying half of the total space.
Adjusting Grid Position
The following properties are used for aligning items within a Grid layout:
-
justify-items : Align items along the horizontal axis
-
align-items : Align items along the vertical axis
-
place-items : Set both of the above properties simultaneously
.container { justify-items: center; /* Center items horizontally */ align-items: start; /* Align items at the top vertically */ } /* or */ .container { place-items: start center; /* Align items at the top vertically, center horizontally */ }
Follow the sections emphasized by asterisks in the code as you type.
What is the most appropriate word to fill in the blank?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help