How I use CSS Grid and Flexbox to Create a One-page Website
CSS Grid for page layout and Flexbox for UI elements
While we can use either CSS Grid and Flexbox for a webpage layout, CSS Grid tends to be used for page layouts while Flexbox tends to be used for aligning UI elements. Let’s create a webpage to see how this pans out in real code. I’ll be using a common design as below:
Step 1 — Plan before coding
The trick to coding layouts is to plan beforehand.
I’ll identify the parent and child elements first based on the layout method. Below are my workings based on the design.
Determine number of rows
I’ll sort the elements on the page into groups horizontally. Elements are represented as boxes, and those along the same (imaginary) line are considered to be in the same row e.g.
article. Were they to start or end on a different line, I would consider them to be on different rows.
Do note that the three elements and its container within
article are ignored here as they are not part of the grid.
Determine the number of rows
I’ll sort the elements into groups vertically. Elements along the same (imaginary) line will be considered in the same column.
Create a guide
After determining the number of columns and rows, I now have a guide that I can follow when coding. In it, I’ll also mark out the grid lines and note down the parent and child elements.