Flexbox

Go back to HTML and CSS Index

Last time, we saw how to change the layout of a page using the float and position properties. Today, we are going to look at a different way of doing just it as well.

As with everything else when it comes to coding, there are many ways to achieving a goal, and one way is not neccessarily better than the other. Sometimes its just about personal preferences.

Flexbox is a layout module that makes it easy to create a flexible responsive layout - with or without the use of float or position.

display: flex

To use the Flexbox module, you have to declare a flex container of some sort. Here's an example:

The HTML

<section class="flex">
<div>1</div>
<div>2</div>
<div>3</div>
</section>
6.10 | Creating a flex container

The CSS

.flex {
display: flex;
}
6.11 | display: flex

Example

1
2
3

The main and cross axis

When working with Flexbox, you work with two axis - the main and the cross axis.

The main axis is declared using the flex-direction property.

.flex {
display: flex;
flex-direction: column | column-reverse | row | row-reverse;
}
6.12 | The flex-direction property

The cross axis runs perpendicular to the main axis, meaning that if the value of the flex-direction property is either row or row-reverse, the cross axis runs down through the columns, while if the value is either column or column-reverse, it runs along the columns.

Example of flex-direction row (standard value)

1
2
3

Example of flex-direction row-reverse

1
2
3

Example of flex-direction column

1
2
3

Example of flex-direction column-reverse

1
2
3

The justify-content property

The justify-content property is used to adjust the elements along the main axis.

.flex {
display: flex;
justify-content: flex-start | flex-end | center | space-around | space-between | space-evenly;
}
6.13 | The justify-content property

Example of justify-content flex-end

1
2
3

Example of justify-content center

1
2
3

Example of justify-content space-around

1
2
3

Example of justify-content space-between

1
2
3

Example of justify-content space-evenly

1
2
3

The align-items property

The align-items property is used to align the items along the cross axis.

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

Example of align-items flex-start (standard value)

1
2
3

Example of align-items flex-end

1
2
3

Example of align-items center

1
2
3

Next up

All of the properties listed above are added to the flexbox container - the parent - but there are also some properties that can be added to the children of the flexbox container...

Next up: Flexbox - child properties