Android
Android Studio
HTML
CSS
Git
SVG
JavaScript
Python
React
Node.js
Express
WebGL
PHP
Mac
Mongo
Crypto
VSCode
Premiere
Recipe
Flutter
React
Web Development
Windows
Just Another Ghost  @jst
Writer at Learning Curve and generally just another ghost! Born of a earth and dust to create. Sooner or later everything we make will be destroyed.

Interactive CSS Flex Tutorial / Flexible Box

#css #flex #layout #tutorial #webdev #front-end
Viewed
14.2K times
semicolon@jst › tutorials › css › flex / flexbox › Thu May 06

Learn CSS Visually! Every single CSS property visualized in this pictorial CSS guide book!

best css book for beginner web developers

⭐⭐⭐⭐ and 1/2⭐ - owned by over 27.1K readers.

Get this CSS book in PDF format, on Amazon or start reading this css book on your Kindle device today!

Get Ghost Messenger
Sign Up Now  -  It's Free!
 / interactive, css, flex, tricks, tutorial, examples, demos, parent, children, container, stretch, justify, align, properties
CSS
FLEX
complete
guide

The Definitive CSS Flexbox Tutorial

Please share on social media or blogs! I spent a long time making this tutorial 🙂

Select Color Theme: This is a comprehensive CSS Flexbox tutorial designed to speed-learn CSS flex. I promise you will learn a lot as quick as possible simply scrolling down animated examples. Pick the color theme of your choice to change all css flex diagrams in this ultimate flexbox guide!

Not everyone likes purple (or violet) and yellow! Change colors of flex graphic in this tutorial by choosing another color combination. Note you can choose Dark Mode, we worked hard to get this to work!

For Beginners (you probably already know this, but just to be complete...)

CSS Flex (also known as Flexbox) is CSS's layout rendering ruleset that consists of parent container and child elements or its items. This tutorial will explore how its properties work and then we'll create some flex layouts.

Flex is a two-fold construct. Some Flexbox properties are intended to be applied to parent and won't work on item elements. Other properties only work on items. Make sure you understand this before moving forward.

It's not uncommon to make the mistake of applying flex properties to its items that are meant to be applied to its parent container. We'll draw distinction between the two in this tutorial.

For now, let's start from the beginning.

If you have a div element that you want to behave like flex:

<div id = "parent"></div>

You can start by defining the parent container for your flex block:

div#parent {
    display: flex;
}

Applying this style to any HTML tag will convert it into an element with flex capabilities.

Many HTML elements have display property set to either inline or block. So there is another thing. Sometimes you will want your flex container to be inline too.

Inline flex containers are set with inline-flex value:

div#parent {
    display: inline-flex;
}

Next step is to decide how many flex items you need and insert them as follows:

<div id = "parent">
    <div>Item 1</div>
    <div>Item 2</div>
    <div>Item 3</div>
    <div>Item 4</div>
    <div>Item 5</div>
</div>

That's enough to get started. Now all you need to do is learn how flex properties work.

How you want your layout to adapt to its content is determined by flex properties. The same goes for aligning items relative to other items in the set.

Let's take a look at Flex properties next.

CSS Flex Train Station Game (play an interactive css flex challenge)

Learn CSS Flex by playing this CSS Flexbox Train Station game!

Park your flex train at provided ghost train station. Each train car must perfectly match position of the ghost train. You can accomplish this by changing flex properties and values in source code window below.

Details matter. Pay close attention to direction of each car in every challenge.

How To Play. To pass this challenhallenge align your train with the ghost train by changing flex properties. They will be applied to the parent container to align flex ege align your train with the ghost train by changing flex properties. They will be applied to the parent container to align flex elements represented by train cars. Click Park Button to test your code when you're ready.

Flex Challenge 1 (see all flex challenges here)

class = "flex no-select"

style = "height: 300px; overflow: hidden; position: relative; justify-content: space-evenly">

Get your flex train wagons parked at shown location to complete the challenge and go to next level.

Solution Hint (Click to unfold)

Hint: All you have to do is add 2 new properties justify-content and align-items to parent container and assign each a value! But which ones and why? Not sure? Head over to our CSS Flex Definitive Guide (it will teach you everything you need to know to pass this challenge) and then come back here.

Flex Container Code

Park

Fun fact. The wheels inside each flex element are also flex elements.

Layout Anatomy - Main Axis and Cross Axis

Unlike regular HTML elements CSS flexbox (flexible box) container has two axis called Main-Axis and Cross-Axis.

1
2
3
Main - axis
justify
Cross - axis
align

Here's the same set of items 1, 2 and 3 with 4 possible flex-direction values.

row
row-reverse
column
column-reverse

Axes cannot be combined. Only one axis can be used at a time.This is only an example.

Flex is inherently not a grid. It has one continuous lane of content which can flow in one direction at a time (in the direction of rows or columns on one axis at a time.) Items inside a flexbox container can break into multiple rows and even create grid-like layouts, but not when using its default settings.

There is only one active flow of direction that all items follow. It's either horizontal on main-axis (default behavior) or vertical on cross-axis. You can swap axis by changing flex-direction property.

By default, inner content overflows parent container without breaking to next row (but still remains visible on the screen.) This is when the sum width of all items don't fit width of the parent container.

Items can skip to next line, but you'll need to set flex-wrap to wrap if you need to create a grid-like layout using flex. Or if you simply need to create a multiple row layout with varying item dimension. You're going to learn special tricks for getting your flex grid behave just the way you want it to.

By default Flex decides when next item of your content should break to next row. But there are properties you can tweak to create a perfect grid-like layout.

How To Center Content Vertically and Horizontally

One of first things you want to learn about flex is how to center items inside a flexbox div element both vertically or horizontally. Before going into more advanced examples, here's illustration of centering an item:

Item

Simple trick to center any content using flex

Just set display: flex, justify-content: center and align-items: center to parent container. Other than that you might also want to explicitly set width and height of the item. Generally flex will calculate spacing based on content's actual (calculated) width and height.

This will center inner text as well as any div elements. Moreover, this setup will also center the row of all items when there are multiple items present in your parent container. (As you'll see in the following examples.)

This one trick is enough for building many minor designs like CSS buttons, centering progress bars, or simply centering an image inside an HTML element.

And while centering items is important, there is so much more to making layouts with flex.

Flex Properties

Simple Flex item

In this tutorial we're going to use this item specimen for all simple examples.

The first item is important. By default it's placed at flex-start. But its placement can be changed in reverse by flex-end.

A

Flex items don't automatically adapt to container size. So let's assign some values to make a basic box:

.item {
    font-size: 28px;
    font-weight: bold;
    border-radius: 8px;
    min-width: 100px;
    line-height: 125px;
    text-align: center;
    background-color: var(--flex-item-bg);
}

When making your own flex layout make sure to define some basic dimensions for your default items. Flex items can stretch and change size depending on content.

Default settings

Example of default flex settings with multiple items:

A
B
C

Now that we have multiple items it gets more interesting.

Direction and Orientation

Generally you should decide whether you need a row or column-based layout first and go from there. Left to right is the default, which at first seems to behave similar to inline or inline-block content.

The direction in which items are going to flow is determined by flex-direction property where row is the default value (this means by default items will flow from left to right on Main axis.) Whereas setting flex-direction to column will swap the axis and items will flow from top to bottom.

Let's take a look at flex-direction values

row → (default)

Items flow from left to right with direction: row (default).

1
2
3
4
5

Flex feature set also offers a number of "reverse" verions of some of its properties.

row-reverse ←

Items flow in opposite direction or in reverse order with flex-direction: row-reverse

1
2
3
4
5

column ↓

Items flow from top to bottom with flex-direction: column

1
2
3
4
5

column-reverse ↑

Items flow from top to bottom with flex-direction: column-reverse

1
2
3
4
5

flex-direction: column-reverse ↑

Items flow upward from bottom to top with flex-direction: column-reverse.

This is the opposite of previous example.

Controlling Space Between Items

Spacing between items on Main Axis and Cross Axis is controlled by a set of values assigned to align-content and justify-content properties. They will be described next in this flex tutorial.

An example of spacing content based on flex direction would be justify-content property which determines amount of either vertical or horizontal space between items. But which one is it? Item flow direction depends on what's in your flex-direction property, as seen from the two examples above.

This will start to make more sense as we move forward.

justify-content

Horizontal spacing with justify-content and flex-direction: row (default)

To achieve horizontal spacing use justify-content property together with flex-direction: row

(But keep in mind flex-direction: row is the default setting.)

In this case justify-content property determines horizontal spacing between your flex items.

Here's default layout with justify-content set to space-evenly value applied to parent element:

A
B
C

Hint: Do not apply this property to items, it's not going to work. Do apply it to parent.

Content can be justified using numerous values for spacing. When to use which depends on the type of layout you're building. Sometimes you just have to figure out which spacing works for what you're trying to create.

This often requires trial and error approach. To save some time, here are diagrams explaining all different spacing styles. Click on play flex animation button to trigger an interactive animation and see how one of the core features of CSS flex works.

Animated JUSTIFY-CONTENT Examples

stretch

A
B
C

space-between

A
B
C

space-around

A
B
C

space-evenly

A
B
C

center

A
B
C

flex-end

A
B
C

flex-start

A
B
C

There is a reason why flex is called flexbox. It's a flexible box! But what does that mean? The layouts will automatically adjust to available space relative to parent element and item size. Click the button below to see how it works. Each item and space around it constitute to the whole of the design!

Play Flex Animation

You can bookmark this example separately at justify-content examples article.

Changing Flex Direction To Swap Axis

You can imitate axis swap by setting flex-direction: column. That's exactly what we did in this next example! To be exact, what was the cross-axis is now main-axis. The rest of the rules stay the same.

Note that justify-content property remains set exactly in the same way as it is in previous example: it remains stretching across main-axis (which has changed direction and now points from top down.)

stretch

space-between

space-around

space-evenly

center

flex-end

flex-start

A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C

Of course this is a fundamentally different layout. Here table columns were used instead of rows as parent container for each example.

This time spacing between items will be applied in vertical dimension (on the cross-axis.) You don't have to change justify-content property to align-content. Everything flips automatically.

Play Flex Animation

Is It Possible to Create a Grid with Flex?

You can see how flex is by design doesn't function like a grid, so you can't specify align in two dimensions at the same time as long as there is one stripe of content (in either direction.)

But at one point you will want to "break lines" in your linear content to create grid-like layouts. So naturally, next thing you want to learn is how to wrap lines of content.

How to create a grid with flex is shown in following examples.

Wrapping Flex Lines Forward and in Reverse

This section is an introduction to flex-wrap property whose default value is nowrap.

flex-wrap property can be set to nowrap, wrap and wrap-reverse.

All 3 values produce different results. Let's take a look at visual examples of what happens here.

By default flex container will not wrap your content. In which case it acts as a weird imitation of something similar to overflow: hidden;, except it doesn't really stop rendering your content. No matter how many items you have they will "overflow" off the edge of your main container.

Here's an example of flex container with too many items to fit on one line:

A
B
C
D
E
F

And here is the same flex example with flex-wrap set to wrap:

A
B
C
D
E
F

A value of wrap-reverse will produce the following result:

A
B
C
D
E
F

The first item is now positioned in lower left corner and the items wrap upward. Note that the direction flow of items (from left to right) is still identical to previous example. We only changed direction of the wrap, not direction of the items on the axis lane.

We've taken first step toward creating grid-like flex layouts!

There is more to flex direction and flex wrap. You can use a shorthand property flex-flow which allows you to set them together. And if you want to learn that, expand the next section.

Shorthand property: flex-flow

Insert flex-flow content here

Next thing you want to learn is align-content property.

ALIGN-CONTENT

Note: This property only works when there is more than one row of items.

The align-content property works similar to justify content, but on another axis (the cross-axis by default.)

Otherwise it has no effect. After all, what would it mean to stretch just one row of items on Cross-axis? At that point there are simply no other rows to compare space between.

This is why aligning content comes into play only when you have more items than can fit on one line (row.) If that's not the case in your layout, changing align-content to any value has no effect.

This is a huge point of confusion for beginners. Most other CSS styles affect the element in some way. But when learning flex for the first time it's possible to really feel dumbdounded at the fact that it seems to be not working at all (until you have more than one row of items.)

So let's create a multi-row flex container and apply different values to align-content property.

Example of align-content with multiple rows

(This also means it requires flex-wrap set to wrap)

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
unset
space-between
space-around
space-evenly
center
stretch

Click on the buttons to change value of align-content property and compare it with previous examples where we used justify-content. The effect is the same but works only when there are multiple rows.

What is the #1 reason stretch doesn't work?

Note that stretch is unique from other values. There are times when flex stretch doesn't work. When using stretch also make sure the sum of all item sizes is at least 100% of the size of the container in that dimension. In this align-content demo (above) item height was explicitly set to 21.59% relative to container height.

Flex Chessboard

Can we make a CSS flex chessboard? Sure why not? The standard UTF-8 set offers us an image for every single chess piece. We've already looked at how to align content to center in both dimensions. The same strategy can be used here. This isn't a perfect solution, some values had to be tweaked manually.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Flex chessboard source code

The flex chessboard parent container:

#flex-chessboard-example {
    width: 100%;
    height: auto;
    justify-content: stretch;
    align-content: stretch;
    height: auto;
    margin: auto;
    flex-wrap: wrap;
    flex-flow: row wrap;
    padding: 50px;
    background-color: #5a3434 !important;
}

Chessboard square:

.chess-box {
    min-width: 109px;
    font-size: 58px !important;
    margin: 0;
    padding:0;
    font-weight: normal;
    justify-content: center;
    item-align: center;
    margin: 0px;
    border-radius:0;
}

The box-shadow property was used to create subtle shadow for each square on the chessboard.

Regular (white) chessboard square:

.chess-box {
    background: white;
    box-shadow: inset 8px 8px 10px #d0d0d0, inset -3px -3px 10px #a9a9a9 !important;
}

Black background square:

.b {
    background: #222 !important;
    box-shadow: inset 8px 8px 10px #111111, inset -3px -3px 10px #636363 !important;
}

This complete CSS Flex tutorial describes every single flex property with visual diagrams. Each example demonstrates how parent and child elements work when different property values are applied. You can easily copy and paste the flex source code from each example by clicking on copy button.

jst
Just Another Ghost @jst
Writer at Learning Curve and generally just another ghost! Born of a earth and dust to create. Sooner or later everything we make will be destroyed.

I've already written a comprehensive css flex overview on Semicolon in the past. So why another tutorial? The first tutorial was a bird's eye view guide. In this one I wanted to focus on details and provide starting point source code examples that can be copied and pasted into your project.

Table of contents:

  1. Introduction for beginners
  2. Layout Anatomy - Main Axis and Cross Axis
  3. Direction and orientation
  4. Flexbox properties
  5. Align and Justify
  6. Practical layout examples
  7. Terminology

Learn CSS Visually! Every single CSS property visualized in this pictorial CSS guide book!

best css book for beginner web developers

⭐⭐⭐⭐ and 1/2⭐ - owned by over 27.1K readers.

Get this CSS book in PDF format, on Amazon or start reading this css book on your Kindle device today!

Get Ghost Messenger
Sign Up Now  -  It's Free!
Write For Us
Sign Up Now  -  It's Free!
© 2021
DM Coming Soon
f f