W04 Learning Activities: Using CSS Layouts
Overview
Mastering CSS Flex and Grid can be challenging. This activity highlights some of the most relevant layouts and the principles behind them.
Prepare
When do I use CSS Flex versus CSS Grid?
Depending on the desired layout, you can often make either method work. You can even use them together, such as using flex to align items within a grid item.
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 generally more robust, allowing you to create two-dimensional layouts for common structures like tables, calendars, merged cells, and more.
- 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
-
flex-direction: (row/column);
(row is default).display: flex; flex-direction: column;
-
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;
Activity Instructions
- Navigate to this CodePen ☼ CSS Layout Exercises
- Complete the three exercises to the best of your ability. The following images are screenshots of the
solutions:
Check Your Understanding
Example: CodePen ☼ Layout Exercises - Solution