CSS Layouts
Overview
Working with CSS Flex and Grid can be a challenge to master. This activity attempts to highlight some of the most relevant layouts and principles behind those layouts.
Prepare
When do I use CSS Flex versus CSS Grid?
Often, depending upon the desired layout, you can often make either method work. Yes, you can use them together such as using flex to align items within a grid cell.
Choose Flex
- Simple Layouts: CSS Flex is ideal for one-dimensional layouts like navigation, or any group of items that need to be shown side by side or one on top of the other.
- Alignment: Flex is great at aligning items horizontally or vertically.
- Dynamic Content: Flex is often ideal for layouts with dynamic content where items sizes may vary.
Choose Grid
- Complex Layouts: CSS Grid is more robust generally in that two-dimensional layouts can be created that require common structures like tables, calendars, merged cells, etc.
- Fixed Width Layouts: Grid is suitable for fixed-width layouts, where item sizes are known.
- Overlap and Layering: Grid supports overlapping and the layering of the items.
Common Layout Methods
-
Define the direction of the Flex items using
flex-direction: (row/column);
(row is default).display: flex; flex-direction: column;
-
Centering Horizontally and Vertically: The following code centers the child item both
horizontally and vertically using CSS Grid. Of course, this code is applied to the parent, grid
container.
Centering can also be controlled with the following code for both Flex and Grid:display: grid; place-items: center;
display: flex; /* or grid */ justify-content: center; align-items: center;
Grid
Activity Instructions
- Navigate to this CodePen: WDD Layout Exercises
- Log into your CodePen account. If you do not have an account, you can create one for free in order to
copy(fork) useful pens and create your own. It is not required, however, you will not be able to save your work
on CodePen and can skip the copy(fork) step.
Accounts at CodePen are free.
You can use your own Google , GitHub or Facebook acount or even use an email of your choice to sign up.It is highly recommended that you obtain an account to manage your own snippets of work and fork useful pens that you find. You are not absolutely required to get an account as you can work on the material for free and skip copying (fork) the pen, but it will not be saved.
- Fork (copy to your own account) the Pen.
- Complete the three exercises to the best of your ability. The solutions will look something like this:
Check Your Understanding
A solution CodePen is found at: WDD Layout Exercises Solution
Additional Resources
The following, carefully selected resources support a deeper understanding of the principles of modern CSS layouts.
- 10 Modern Layouts (22 min) - Chrome for Developers
- Align the Grid (4 min) - gridbyexample.com
- Align Grid Items (4 min) - gridbyexample.com