Introduction to CSS Flexbox

Using the CSS flexbox method to layout the content of web pages in responsive grids of rows and columns.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Understand the concept of flexbox parent-child elements.
  • Use the CSS flexbox method to layout the content of web pages in responsive grids of rows and columns.

You can view finished version of the sample web page you will create in this Tutorial by clicking the link below. The finished sample will open in a new tab of your web browser.

padding page-11.html

About CSS flexbox

CSS flexbox is one of two layout methods web designers use to arrange web page content into rows and columns. (The other is called CSS grid.)

padding padding

Flexbox: parent and child elements

The flexbox layout technique is based on the concept of parent and child elements.

  • A parent element will typically have a class name of container-flexbox, wrapper-flexbox, flex-wrapper or similar.
  • A child element in flexbox layouts is commonly known as an item. For this reason, you will see child elements with class names such as item-top and item-right.  When the flexbox method is used to create multi-column layouts, however, you will see child elements with class names such as col-2, col-3 and col-4.

Below is an example from VS Code of the HTML tags for creating a three-column layout with flexbox.

padding

It is the parent element in a flexbox layout that makes it a flexbox layout. In particular, it is one CSS style rule of the parent element. See below.

/* == FLEXBOX PARENT CONTAINER == */
.container-flexbox { 
   display: flex; 
}

This one style rule of display: flex is enough to make an element a flexbox parent container.

Updating your sample box model page

In the Introduction to the Box Model Tutorial, you used the HTML div tag to create four ‘little boxes’.

Each one of the four div elements has its own class name and some style properties set in the CSS file. See one example below.

Intro to Flexbox

When displayed in a web browser, the web page shows the four ‘little boxes’ stacked vertically one above the other.

See the sample page-9.html web page below.

Intro to Flexbox

Let’s apply the flexbox layout parent-child method to arrange these four HTML elements side-by-side in a single, four-column row.

  1. In VS Code, open the following web page on your computer that you completed in the Introduction to the Box Model Tutorial:   page-9.html   This should be located in your 📁 websites/exercises sub-folder.
  2. Also in VS Code, open the linked stylesheet for the above web page.   style-9.css   This should be located in your 📁 websites/exercises/assets/css sub-folder.
  3. Save your page-9.html web page with the new name of page-11.html.
  4. Save your style-9.css stylesheet with the new name of style-11.css.
  5. In the head of page-11.html, update the stylesheet link from style-9.css to style-11.css.
    <link rel="stylesheet" href="style-11.css">
    
  6. Also in the head block, copy-and-paste the following to replace the current title and description details:
    <title>HTML5 Sample Flexbox Web Page: Four-column Layout.</title>
    <meta name="description" content="Using CSS flexbox to create a web page with a four-column layout.">   
  7. Save the page-11.html file.

You are now ready to update the web page and stylesheet to HTML5.

Updating your web page to HTML5

Follow the steps below to make your web page HTML5-compliant.

  1. In VS Code, ‘wrap’ (enclose) the four div elements in the page-11.html file within the three opening and closing HTML5 tag pairs of main, article and section.   Near the top of the web page, paste the following just after the opening body tag.
    <main>
    <article>
    
        <section>
    
    Scroll down to the bottom of the page, and just before the closing body tag, copy-and-paste the following.  
        </section>
    
    </article>
    </main>
    
    In VS Code, your page-11.html file should now look as follows. Intro to Flexbox
  2. Save the page-11.html file and view it in your web browser. It should look exactly as before.

Attaching ‘white space’ to the section element

Currently, the ‘white space’ around the four edges of the web page content is set by CSS padding values on the body element.

Change this as follows.

  1. In VS Code, switch to the style-11.css file.
  2. Near the top of the file, just after the RESETS block, delete all the following lines. Intro to Flexbox
  3. Save the style-11.css file.   In your web browser, you can see that the web page content is now positioned directly against the top-left corner of the browser window. Intro to Flexbox
  4. In VS Code, copy-and-paste the following lines to the style-11.css file, to just after the RESETS block.
    /* ======================= SECTIONS ======================== */
    
    /* Regular and larger screens */
    @media (min-width: 1200px) { 
      section { 
          margin-left: auto;
          margin-right: auto;
          padding: 3.5% 0 4% 0; 
          padding-left: calc( (100% - 1140px)/2 );
          padding-right: calc( (100% - 1140px)/2 );
    }
       .section-narrow {
          padding-left: calc( (100% - 920px)/2 );
          padding-right: calc( (100% - 920px)/2 );
       } 
    }
    	
    /* Tablets and smaller desktops */
    @media (min-width: 1025px) and (max-width: 1199px) { 
        section { padding: 3% 10% 4% 10% }
    }
    	
    /* Tablets */
    @media (min-width: 768px) and (max-width: 1024px) { 
        section { padding: 4% 5% 4% 5% }
    }
    	
    /* Larger mobiles */
    @media (min-width: 400px) and (max-width: 767px)  { 
        section { padding: 7% 13% 8% 13% }
    }
    	
    /* Smaller mobiles */
    @media (max-width: 399px) { 
        section { padding: 7% 10% 8% 10% } 
    }
  5. Save the style-11.css file and view the web page in your browser.   Intro to Flexbox

You can see that the web page content is no longer positioned directly against the edges of the browser window.

However, the ‘white space’ around the four edges of the web page content is now set by CSS padding on the section element rather than on the body element.

Adding and styling the parent flexbox container

The next task is to add a new div element to the web page that will act as a flexbox parent container.

  1. In the page-11.html web page, wrap the four div elements within a new, outer div that has a class name of container-flexbox. Intro to Flexbox Use the Tab key to indent the four ‘little boxes’ from the left margin. This will make your HTML code easier to read.
    • The container-flexbox element is now a parent element.
    • The four little boxes, with the class names of bono, edge, adam and larry are now child elements of this parent element.
  2. Save your page-11.html file.

Next, let’s style this new container-flexbox div element so that it acts as a flexbox parent element.

  1. In VS Code, display the linked style-11.css stylesheet file.
  2. Copy-and-paste the .container-flexbox selector with its single – but important – style rule that makes it act as a flexbox parent.
    /* == FLEXBOX PARENT CONTAINER == */
    .container-flexbox { 
        display: flex; 
        justify-content: space-between
    }
    You could add this anywhere in the CSS file. But, logically, it makes the most sense to enter it above the styles for its four child elements, at around lines 76-78. Intro to Flexbox
  3. Finally, update the widths of the four child elements in the CSS file from their current fixed-width value of 220px to a fluid, responsive width of 25%. One example is shown below. Intro to Flexbox
  4. Save your style-11.css stylesheet.

View the page-11.html file in your web browser. It should now look as shown below. Intro to Flexbox

✅  Success. You have now created a multi-column web page layout.

Flexbox columns and gutter spacing

In practice, however, you will want to add two further CSS style rules to your flexbox parent containers, as shown below.

/* == FLEXBOX PARENT CONTAINER == */
.container-flexbox { 
   display: flex; 
   justify-content: space-between; 
   flex-wrap: wrap; 
}

Let’s look first at the justify-content property and its typical value of space-between.

When you arrange web page content in two, three of four columns, you will typically want to include some empty spacing between the columns.

This inter-column spacing is known as the gutter, a term inherited from print design.

padding

The total gutter spacing (of one, two or three gutters) is the space remaining or ‘left over’ after the child elements have filled their defined widths.

A flexbox parent container has a CSS property named justify-content that controls how the gutter spacing is displayed, left-to-right, across the screen.

Unfortunately, the CSS justify-content property has a default value of flex-start that will:

  • Pack or squeeze the child elements at the left of the parent container, and
  • Display the ‘left over’ spacing in a single block at the right of the parent container.
padding padding

To instead distribute this ‘left over’ space evenly between the columns in gutters, you need to override the default value of the justify-content property by entering the value of space-between in the CSS stylesheet.

padding

This will create the desired result of evenly-spaced columns in your web browser.

padding

Adding gutters between columns

Let’s add some gutter spacing to your sample web page. Here are the steps.

  1. In VS Code, display the style-11.css stylesheet.
  2. Update the .container-flexbox selector by adding a new style rule as follows:
    /* == FLEXBOX PARENT CONTAINER == */
    .container-flexbox { 
        display: flex; 
        justify-content: space-between
    }
  3. For each of the four child elements, reduce their width from 25% to 23%. See one example below.
  4. Save the style-11.css stylesheet and then view the page-11.html page in your web browser. It should now look as shown below. Intro to Flexbox

Now, as an experiment, let’s reduce the number of columns of content from four to three.

  1. In VS Code, display the page-11.html web page.
  2. Wrap the first child element inside a comment, so that it will not be displayed by the web browser. See below. Intro to Flexbox
  3. Save the page-11.html file and view it in your web browser. It should now look as shown below. Intro to Flexbox
  4. In the style-11.css stylesheet, edit the width property of the three, non-commented-out child elements by increasing the value from 23% to 31%. See one example below. Intro to Flexbox
  5. Save the style-11.css file and view the page in your web browser. It should now look as shown below. Intro to Flexbox
  6. When finished, edit the web page and stylesheet so that four child elements are again displayed with a width of 23%.

Flexbox and child element wrapping

There is one more CSS property-value pair that you will usually want to apply to your parent flexbox containers.

This property enables child elements to be split or wrapped across multiple rows within a parent element.

Consider the following three-column layout, displayed under a section-wide heading that is above and outside the container-flexbox parent element.

padding

What would happen if you added three more child elements to this layout? The result will be as shown below.

padding

As you can see, the parent container-flexbox forces all six child elements to display on a single row, left-to-right, across the screen.

This is because a parent flexbox container has a CSS property named flex-wrap with a default value of nowrap.

padding

How can you retain your three-column layout – now that it contains six child elements? The effect you want to achieve is shown below.

padding

The solution is to override the default nowrap value of the flex-wrap property by entering a value of wrap for the flexbox parent container as shown below.

padding

There are many other CSS properties and values you can assign to flexbox parent containers. But for most practical web page layouts, setting values for the display, justify-content and flex-wrap properties is sufficient.

padding

Creating a two-row, four-column grid layout

Next, let’s edit the sample web page so that it displays content in a grid of two rows with four columns in each row. Follow these steps.

  1. In VS Code, in the page-11.html file, select, copy and paste the four div child elements within the container-flexbox parent element.
  2. Save the page-11.html file and view the web page in your browser. padding As you can see, flexbox has squeezed all eight child elements onto a single row.   This is despite each child div element having a set width of 23% in the stylesheet.
  3. In VS Code, display the style-11.css file and replace the current .container-flexbox style rules with the following.
    /* == FLEXBOX PARENT CONTAINER == */
    .container-flexbox { 
        display: flex; 
        justify-content: space-between;
        flex-wrap: wrap
    }
  4. Save the style-11.css file and view the web page in your browser. It should now look as shown below. padding

Making your layout grid responsive

In this final exercise, let’s ensure your sample web page displays appropriately on devices with smaller viewport widths.

In practice, you will want the content to display in four columns only on non-mobile screens. And as a single, full-width column on mobiles. This requires just one addition to the linked stylesheet.

  1. In VS Code, in the style-11.css file, copy-and-paste the lines below at the end of the file.
    /* === COLUMN WIDTH ON MOBILES === */
    @media (max-width: 767px) { 
      .bono, .edge, .adam, .larry { 
        width: 100%; 
      }
    }
  2. Save the style-11.css file and view the web page in your browser at different screen widths. It should now look as shown below. padding

✅ All done. You have now completed this exercise.

Updating your website home page

Now that you have updated and styled a new web page, let’s add a hyperlink to it on the ‘home page’ of your web site. Follow the steps below:

  1. In VS Code, open this HTML file in your ‘main’ websites folder:   index.html
  2. Copy-and-paste the following new line to your web page, directly under the line that contains the link to the page-11.html web page.
    <p><a href="exercises/page-11.html">Responsive grid of rows and columns</a></p> 
    

Save your index.html web page and view the result in your browser.

Uploading your files to GitHub

After finishing your web page and stylesheet, you are now ready to upload them to your account on GitHub.

  1. Open a new tab in your web browser and go to GitHub.com. If you are not already signed in to your GitHub account, sign in now. github-signin
  2. On your GitHub home page, click the ‘repo’ that holds your web pages. Its name will look as follows, where username is your chosen username on GitHub.   username.github.io github-signin
  3. On the next GitHub screen displayed, near the right of the screen, you can see a button named Add file. Click on it. github-upload-portfolio
  4. From the dropdown list displayed, choose the option Upload files. Project Animation Google Fonts
  5. In File Explorer (Windows 10) or Finder (Apple Mac), drag-and-drop your index.html file and your 📁 exercises sub-folder to upload them to your repository on GitHub. Introduction to HTML
  6. Scroll down to the bottom of the GitHub screen, and accept or edit the short message (Add files via upload) in the Commit changes box.
  7. Finally, click the green Commit changes button to upload your files. Project Animation Google Fonts

Your updated home page and sample web page are now published on GitHub at web addresses similar to the following:

https://username.github.io/index.html
https://username.github.io/exercises/page-11.html

It may take a few minutes for your uploaded files to appear on GitHub.