WDD 130: Web Fundamentals

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
Choose Grid

Common Layout Methods

The following are common layout tasks that can be easily accomplished with Flex and Grid.

Aligning Items in a column
Flex Direction Column

To align items in a column, you can use Flex, and set flex-direction: column; (row is default).

display: flex;
flex-direction: column;
Centering Vertically and Horizontally
Layout center middle with Flex/Grid

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.

display: grid;
place-items: center;

Centering can also be controlled with the following code for both Flex and Grid:

display: flex; /* or grid */
justify-content: center;
align-items: center;

Activity Instructions

  1. In the week04 folder, open the file named layout-exercises.html and the layout-exercises.css file in the week04 styles subfolder.
  2. Use Live/Five Server to open the file in the browser.
  3. Complete the three exercises contained in that file. The following images show what the solution should look like:
    Layout Exercise 1 Output
    Layout Exercise 2 Output
    Layout Exercise 3 Output
Check Your Understanding

Attempt to complete the exercises on your own before looking at this example solution.

  1. .flex {
      background-color: #aba;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .grid {
      background-color: #abb;
      display: grid;
      place-items: center;
    }

    * Either place-items or align-items/justify-content can be used to for exercise.

  2. .container2 {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }
  3. .container3 {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;  /* or grid-template-columns: repeat(3, 1fr); */
    }
                  
    .columns-3 {
      grid-column: 1/4; /* or grid-column: span 3; */
    }

There is also a solution file is named layout-exercises-solutions.html and the corresponding CSS file is named layout-exercises-solutions.css in the week04 folder.