Flexbox: The Complete Guide

This guide will equip you with Flexbox; go beyond it. With practical exercises focusing on fundamentals and advanced topics.

· 17 min read
Cornelius Emase

Cornelius Emase

topics

Introduction

This guide introduces you to the basics of Flexbox, a powerful CSS tool that simplifies creating functional and modern layouts. The flexbox has made the web pages more intuitive, interactive and responsive, enhancing user interactions and satisfaction

Highlights

  • In this guide, you'll become a master of the Flexbox model.
  • You will learn to perfectly align and distribute elements.
  • And finally, we will have a challenge and a practical guide with which we'll solve it together.

Prerequisites

Gear Up: Have your preferred code editor ready, and let's do magic with Flexbox. You should be familiar with the basics of HTML and CSS, how they work.

Definition

Flexbox is a powerful layout model in CSS that offers a more intuitive and efficient way for developers to arrange elements on a webpage. It replaces the older float-based approach, providing greater control over alignment, distribution, and responsiveness.

There are various places you can use Flexbox when you need to build responsive layouts, align and distribute content, and build complex UI (nested containers and dynamic content arrangements).

Note: Flexbox is a one-dimensional layout method, that primarily focuses on arranging elements along a single axis at a time. This axis can be horizontal or vertical.

Alternatives to Flexbox

1. Floats. While float is still being used, it is considered less effective and prone to layout issues.

2. CSS Grid layout. grid is another powerful tool for creating complex layout, it is a two-dimensional layout with rows and columns and are appropriate for larger-scale layouts.

The main idea behind Flexbox

In the early days, developers would need to come up with complicated mathematics to come up with sizes to arrange and align items on their applications. There was need to resolve these tiresome calculations, Flexbox came in handy, which then provides a flexible "box" model where child objects can be sized, matched, and shared based on predefined rules.

The benefits of using flexbox

Flexbox has made it easier to come up with simple and easy layouts for responsive web pages. You could have done it before with a combination of floats and position properties, which were more complex and tiresome at the time.

Flexbox has made it all easier, simple to make web apps more responsive. You can now be able to perform the following with flexbox:

  • Flexbox makes it easier to design flexible and responsive layouts without using floats or positioning.
  • Automatically adjusts the space between elements to fit the container size, ensuring consistent spacing.
  • provides straightforward properties to align and center items both horizontally and vertically.
  • Adjusts elements based on their content, making it ideal for dynamic interfaces.
  • Allows easy reordering of elements without changing the HTML structure.
  • Minimises the need for complex CSS rules and hacks, resulting in cleaner and more maintainable code.

Knowing the benefits to flexbox derives the need to work around with them, let’s explore some of the concepts in it.

Main axis and cross axis

These axes are crucial for effectively using properties like `justify-content` (aligning items along the main axis) and `align-items` (aligning items along the cross axis).

The exes (main or cross) can be different either vertically or horizontally based on the value of `flex-direction`.

Main axis:

The primary axis along which flex items are laid out. It is defined by the flex-direction property.

  • row (default): Main axis is horizontal, running from left to right.
  • column: Main axis is vertical, running from top to bottom.
Image

Cross axis

The axis perpendicular to the main axis. It runs in the opposite direction to the main axis.

  • For row, the cross axis is vertical (top to bottom).
  • For column, the cross axis is horizontal (left to right).
Image

Let's get it done with an example

To begin, you can create a folder, name it whatever you want, and then create two files, index.html and styles.css.

Flex container

The flexbox container, also known as the parent container, is the foundation of flexbox, holding the child elements you want to array using flexbox properties.

You can follow along with the code to practice, just paste the code to experiment with us as we go along.

Setting Up Flexbox

To enable Flexbox on a container, you simply set the display property of the element to flex:

.flex-container {
   display: flex;
 }

Flexbox has properties; these are:

  • Flex-direction
  • Flex-wrap
  • Flex-flow
  • Justify-content
  • Align-items
  • align-content

When you set the container flex, by default, the container would flex its items on the row, direction property. The images below would justify the above properties, and you can do a checkup on your browser with the code provided alongside.

Flex direction.

The flex direction defines the main axis along which items are laid out. Options include:

  • row (which is the default): Arranges items from left to right (horizontal, x axis).
  • column: arranges items from top to bottom (vertical - y-axis).
  • row-reverse: arranges items from right to left (horizontal reversed).
  • column-reverse: arranges items from bottom to top (vertical reversed).

You can check the image below and do check up with the code sample provided to experiment it.

Image
.flex-container {
   display: flex; 
   flex-direction: column; /*Stack items vertically */
}

Flex wrap

This property controls how flex items wrap onto multiple lines if they don't all fit on a single line within the container. The flex-wrap property provides flexibility in arranging items within a flex container.

Flex wrap can be useful when you need to let your items begin in a new line, rather than squeezing themselves into one line. The flex property has the following values:

  • no-wrap
  • Wrap
  • Wrap-reverse.

flex: no-wrap

This value prevents flex items from wrapping. All items will fit on a single line, and they will shrink to fit if necessary.

You could try this code here, with the flex - nowrap.

.nowrap { 
   flex-wrap: nowrap;
}
Image

flex-wrap: wrap

This value allows flex items to wrap onto multiple lines from top to bottom.

.nowrap { 
   flex-wrap: wrap; 
}
/*Items wrap onto multiple lines if needed */ 
Image

flex-wrap: wrap-reverse

This value allows flex items to wrap onto multiple lines from bottom to top, the opposite of wrap. You can set it using wrap-reverse value. The image below demonstrates how reverse works, it moves overflow items to the next top line instead of the next line below.

Image

Flex flow

This is a shorthand property for setting both flex-direction and flex-wrap in one declaration. Try with this code here:

.column-wrap { 
   flex-flow: column wrap;
}

/* This example arrange items in a column and wrap if needed */
Image

The flex-flow property simplifies setting the direction and wrap behavior of flex items. Instead of writing two separate properties (flex-direction and flex-wrap), you can use flex-flow for a more concise and readable style.

Justify content

This property distributes flex items along the main axis of the container.

.justify-start { 
   justify-content: flex-start | flex-end | center | space-between | space-around;
}
Image

Even though space-evenly and space-around might appear similar, they differ in spacing distribution. Space-evenly ensures equal space around all items, while space-around gives half the space at the edges compared to the space between items. This results in larger gaps between items in space-around.

Align Items

This property aligns flex items along the cross axis of the container (perpendicular to the main axis).

Image
.align-start {
   align-items: flex-start | flex-end; | center | baseline | stretch;
}

Step-by-Step Demo for align-items

We will do a step-by-step guide where we will experiment with a page containing articles and how it affects the alignment of articles by using the different values of the align-items.

Setting Up the HTML Structure

We will set up our project folder structure with HTML and CSS files. You can then fill in the HTML content and let’s go together. You can find the code here on this repo if you're going along with us.

Applying align-items property

We'll explore different values of align-items in the .main-content container to see how they affect the alignment of the articles.

.main-content {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  height: 75vh;
  align-items: flex-start; 
}

/* Aligns items at the start */

By aligning items flex-start, the items will be at the top, at the start of the cross axis. If you have flex-direction: column, you will have the articles aligned on the start, but in column-wise - on top of each other.

Image

align-items: flex-end

This will align articles at the end of the cross axis (bottom in this case).

.main-content {
  // the rest of the code
  align-items: flex-end;
}
Image

align-items: center

The articles will be centered along the cross axis (vertically within the .main-content container.) in this case. You can use align-items: center to achieve that.

.main-content {
  // the rest of the code
  align-items: center; 
}
Image

align-items: stretch

This is the default value of align-items, if you don't specify the value, it will stretch by default.

.main-content {
  // the rest of the code
  align-items: stretch; 
}

The articles will stretch to fill the height of the main container.

Image

align-items: baseline

This will allow articles to be aligned along their text baselines. We can make some adjustments (titles having different font sizes to see the effect well) to some of the articles.

.main-content {
  // the rest of the code
  align-items: stretch; 
}
Image

Align-content

The align-content property is used to align the flex lines within a flex container when there is extra space on the cross-axis. It is different from align-items, which aligns items within a single line.

This property can take any of the following values:

  • stretch (default)
  • flex-start
  • flex-end
  • center
  • space-between
  • space-evenly
  • Space-around

We will use flex-wrap property set to wrap to better demo the align-content property. We will use our code earlier to demonstrate.

align-content: stretch

When justify-content is not specified, the default behavior aligns items starting from the flex-start without any spacing modifications. This example uses align-items: stretch to make sure all items stretch to the height of the container.

//Html file

<div class="container">
  <div class="box">one</div>
  <div class="box">two</div>
  <div class="box">three</div>
  <div class="box">four</div>
  // .... the rest of elements
</div>

//Stylings
.container {
    display: flex;
    height: 80vh;
    flex-wrap: wrap;
    align-items: stretch;
    border: 2px solid #a79797;
    gap: 10px;
    padding: 2px;
    background-color: #A47467;
}
.box {
    background-color: whitesmoke;
    border-radius: 10px;
    padding: 10px;
    width: 150px;
    border: 2px solid #A47467;
    font: bolder 1.5rem Arial;
}
Image

align-content: flex-start

This aligns items to the start of the container.

Image

align-content: flex-end

It displays values to the end of the main axis.

Image

align-content: center

This one displays values in the middle of the container.

Image

align-content: space-between

This will place the first flex item at the start of the main axis and the last flex item at the end of the main axis. The remaining space along the main axis is distributed equally between the items.

Image

align-content: space-evenly

This will distribute space equally around all flex items, ensuring equal space between each item and the container edges.

Image

align-content: space-around

This will distribute space evenly around all flex items, with half-size space on the edges compared to the space between items.

Image

Child Elements (Items)

These are the individual elements that you want to arrange and style using Flexbox properties and are child elements of a flex container.

The flex item properties are

  • Order
  • Flex-grow
  • Flex-shrink
  • Flex-basis
  • Flex
  • Align-self

The order property

This property allows you to override the default order of flex items based on their HTML structure. It accepts an integer value, and items with lower order values will be positioned before items with higher values.

Image
 <div class="container">
    <div class="box box1">one</div>
    <div class="box box2">two</div>
    <div class="box box3">three</div>
    <div class="box box4">four</div>
 </div>

// css stylings

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  background-color: #222222;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #f3eeed;
  padding: 20px 0;
  background-color: #6f6a6a;
}

.container {
  padding: 2px 5px;
  display: flex;
  height: 800vh;
  gap: 10px;
}

.box {
  background-color: whitesmoke;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
  font: bolder 1.5rem Arial;
}

.box1 {
  order: 3;
}

.box2 {
  order: 4;
}

.box3 {
  order: 1;
}

.box4 {
  order: 2;
}

In the above example, even though we have our elements starting from one, the third div ('three' element) comes first in the HTML, so we set its order to 1, placing it at the beginning of the layout. You should remember that the order value must be a number, default value is zero (0).

The flex-grow property

This property defines how much a flex item can grow in relative to the rest of the items, to fill the available space within the container after the initial sizing of all items. It accepts a numeric value (including decimals); a value of 0 means the item won't grow, and a higher value indicates a greater ability to grow.

 <div class="container">
        <div class="box box1">one</div>
        <div class="box box2">two</div>
        <div class="box box3">three</div>
        <div class="box box4">four</div>
 </div>

// styling
.box1{
   flex-grow: 1;
}

.box2{
   flex-grow: 3;
}

.box3{
   flex-grow: 1;
}

.box4{
   flex-grow: 1;
}
Image

We have maintained the CSS styles.

The flex-shrink property

This property defines how much a flex item can shrink if there's not enough space in the container to accommodate all items at their preferred sizes. The value must be a number, and the default value is 1.

Image

You will notice that the fourth div has a larger value, which is the default size that we set initially. As far as we need all other elements to shrink, we set the fourth element shrink value to 0, to denote that it won't shrink.

   <div class="container">
        <div class="box">one</div>
        <div class="box">two</div>
        <div class="box">three</div>
        <div class="box">four</div>
        <div class="box box-4">four</div>
        <div class="box">five</div>
        <div class="box">six</div>
        <div class="box">seven</div>
        <div class="box">eight</div>
        <div class="box">nine</div>
        <div class="box">ten</div>
    </div>


// stylings
.box-4 {
     flex-shrink: 0;
}

The flex-basis property

This property specifies the default size of a flex item before the available space in the container is distributed using flex-grow and flex-shrink. It can be specified in pixels, percentages, or other CSS units.

 <div class="container">
      <div class="box">one</div>
        <div class="box">two</div>
        <div class="box">three</div>
        <div class="box">four</div>
      <div class="box box-4">four</div>
  </div>


// styles
box-4 {
  flex-basis: 600px;
}
Image

In the above image, you will notice that the fourth element is greater with than the rest, which we set earlier to be 200px. The flex basis will override it and sets the new value.

CSS centering using flexbox

The challenge

Well, it is time we do a challenge. With the above knowledge, you are now ready to solve the challenge with me. The most frequent problem, trending on the internet:

How do you center elements?

We will have the simplest solution using flexbox and margin to solve this challenge. Let's get into it.

There are always two display values, block elements (e.g. headings, divs etc) and inline elements (images, links … etc).

Centering a button

Assuming we have two buttons that require centering, we can achieve this by applying the CSS display: flex to the container that holds the buttons (parent element). You should also take into account that a button is an inline element.

<div class="explore--btns">
  <button class="btn">Learn CSS</button>
  <button class="btn">Learn FlexBox</button>
</div>

Styling

.explore--btns{
   display: flex;
   justify-content: center;
}

.btn{
    margin: 3em 1em 0 1em;    
    background: #dfe1e5;    
    border: none;
    padding-top: 8px;
    padding-bottom: 8px
    padding-left: 16px;
    padding-right: 16px;    
    border-radius: 4px;    
    font-size: 14px;   
    cursor: pointer;
}
Image

In the above assigning a class .explore--btns a property display to flex makes our elements(buttons) flexible. The justify-content aligns our elements at the center horizontally.

Center the buttons vertically

The align-items property specifies the default alignment for items inside a flexbox container.

Using the example discussed above, let's center our elements vertically using align-items.

.explore--btns{
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;
}
Image

We've set the align-items property value to center. The justify-content property set to center allows horizontal alignment of elements and their position at the center of the page.

Note: It's important to keep in mind that we should define the height of the container holding the items beforehand when you need to center or align items across the container.

Practice with Flexbox Games

You can try these fun and engaging games that will provide you hands-on experience with Flexbox.

What next?

KdaSchool presents numerous challenges—any you can imagine. You can tackle one of these challenges hands-on. For instance, try out the salary calculator. Discover this and more challenges here.

Embrace the opportunity to learn and grow through practical experience.

Wrap up

To sum it up, knowing how to use these elements effectively can help create a clean and readable layout for a web page. Placing elements in a container in CSS can be a challenging task, but it is an essential skill for developers working on modern websites and can help create a clean and readable layout for a web page. Whether it's horizontally or vertically centering, various techniques and properties can be used, including margin, padding, transform, and flexbox. You can also use it to make responsive web pages. Depending on the type of content being centered and the design requirements, different methods may be more effective.

Thank you for reading! You can check out our challenges to get hands-on experience.

share

Cornelius Emase

Software Engineer | Product Manager | Technical writer |