CSS Flexbox tutorial: How to use flexbox properties
Tags: css, webdev, tutorial, programming
Published: 2023-01-30 19:16:42

The **Flexbox Layout module** of CSS provides an efficient way to layout and align space for any web dev project. Flex layout gives you the ability to alter your item’s width and height to best fill the available space and accommodate different kinds of screen sizes.

In this tutorial, we will introduce you to CSS flexbox and show you how to implement this in your own programs. We will show you some practical examples and examine all the terminology you need to get started.

**This guide at a glance:**
* [What is CSS Flexbox?](#what)
* [Flex container properties](#container)
* [Flex item properties](#item)
* [What to learn next](#next)

<a name="what"></a>

## What is CSS Flexbox?

Crafting intelligent [page layouts](https://www.educative.io/blog/complete-guide-css-positions?eid=5082902844932096) with CSS has been tricky in years past. Before flexbox was introduced, web developers had to use floats and table display hacks, often leading to unexpected issues. The CSS flexbox model introduced a cleaner, modern syntax for crafting intelligent layouts. 

The flexbox model provides an efficient way to **lay out, align, and distribute space** among elements, even when the viewport and element size is dynamic or unknown.

> Flexbox is a **whole CSS module**, not a single property, so there’s a lot to cover to master this powerful tool. We’ll try to cover the most important ones as we go.

To start using the flexbox model, we first define a `flex-container`. Let’s see how that’s done. First, look at some regular HTML.

```html
<ul> <!--parent element-->
  <li></li> <!--first child element-->
  <li></li> <!--second child element-->
  <li></li> <!--third child element-->
</ul>
```

In this code above, you’d call the `ul` the parent element and the `li` the child element. We do the same with the flexbox model. We must first make a **parent element**, called a flexible container.

You do this by setting `display: flex` or `display: inline-flex` for the inline variation.

```css
/*Make parent element a flex container*/
ul {
  display: flex; /*or inline-flex*/
}
```

We can add a bit of styling and [color with CSS](https://www.educative.io/blog/css-color-guide?eid=5082902844932096) to this, as we do below. Take a look at the code below to see how the parent element looks.

```css
/*Make parent element a flex container*/
ul {
  display: flex; /*or inline-flex*/
  list-style: none;
}

li {
  width: 100px;
  height: 100px;
  background-color: #8cacea;
  margin: 8px;
}
```

**Output:**

![Flexbot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9g6eod35kq1ygjei4tk.png)

The unordered list automatically becomes the flex container (parent), and the child elements (the list elements `li`) become the **flex items.** Some properties in the flexbox module apply to the flex items, and some are set to the container.

<br>

### Flex layout

The flex layout is based on `flex-flow directions`. Look at this figure to better understand the ideas behind the flex layout.

![Flexbot layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/huctmfhzvbg8oumpimhb.png)

As you can see, items are laid out following either the **cross axis** (from `cross-start` to `cross-end`) or **main axis** (from `main-start` to `main-end`).

* **`flex-direction`:** controls the direction in which the flex-items are laid along the main axis
* **`main axis`:** this is the primary axis that flex items are laid out along. It is not always horizontal.
* **`main-start`/`main-end`:** flex items are set within a container starting from the `main-start` to `main-end`
* **`main size`:**  an item’s width or height will be the main size (whichever is in the main dimension)
* **`cross axis`:** This is the axis  that is perpendicular to the main axis. 
* **`cross-start`/`cross-end`:** flex lines are set within a container starting from the `cross-start` side to the `cross-end` side
* **`cross size`:** width or height of a flex item is the item’s cross size (whichever is in the cross dimension)

<br>

<a name="container"></a>

## Flex container properties

The flex container is the parent element that holds the individual children or flex items. There are several properties we can use to create the flex container we want. Let's examine the most important flex container properties. 

### display

As we showed above, `display` defines a flex container, either inline or block. 

```css
.container {
  display: flex; /* or inline-flex */
}
```

### flex-direction

`flex-direction` determines the `main-axis`, so it defines the direction that flex items are set in the container. 

> Generally speaking, flexbox is a single-direction layout concept, so they are either in horizontal rows or vertical columns.


```css
.container {
  flex-direction: row | row-reverse | column | column-reverse;
}
```

Technically, “horizontal” and “vertical” aren't terms we use in flexbox. Instead, the `main-axis` default direction feels like `horizontal`, and the `cross-axis` feels like `vertical`.

By default, the `flex-direction` property is set to `row` and aligns along the main axis. If the `flex-direction` property is changed to `column`, flex-items will be aligned along the cross axis.

### flex-wrap

Flex items will try to fit onto one line by default. We can change this with `flex-wrap`. The flex wrap property can take on three values:

```css
//where ul represents a flex container
ul {
  flex-wrap: wrap || no-wrap || wrap-reverse;
  }
```

* `nowrap` (default): flex items are on one line
* `wrap`: flex items are wrapped onto multiple lines (top to bottom)
* `wrap-reverse`: flex items are wrapped onto multiple lines (from bottom to top)

Here is an example of `wrap-reverse`:

```css
ul {
	  display: flex; /*or inline-flex*/
	  list-style: none;
  	flex-wrap: wrap-reverse;
	}
	
li {
	  width: 100px;
	  height: 100px;
	  background-color: #8cacea;
	  margin: 8px;
	}
```

**Output:**

![Flexbot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpojfz4ju42ohqhxkokw.png)

### flex-flow

`flex-flow` is shorthand for the properties `flex-direction` and `flex-wrap`. Together, they define the flex container’s main and cross axes. This is similar to the `border` shorthand.

```css
ul {
	flex-flow: row wrap; /*direction 'row' and yes, please wrap the items.*/
}
```

> Other combinations this could take: `flex-flow: row nowrap`, `flex-flow: column wrap`, `flex-flow: column nowrap`

### justify-content

`justify-content` is for alignment along the main axis. The three flex-items may be aligned across the `main-axis` however you need. This property takes on any of the values below.

```css
ul {
	justify-content: flex-start || flex-end || center || space-between || space-around
}
```

* `flex-start` (default): items are placed at the start of `flex-direction`
* `flex-end`: items are placed at the end of flex-direction.
* `start`: items are placed at the start of the `writing-mode` direction
* `center`: items are centered 
* `space-between`: items are evenly distributed 
* `space-around`: items are evenly distributed with equal space between and around them

### align-items

`align-items` defines how your flex-items are laid out on the cross axis. It can be set to any of these values:

```css
/*ul represents any flex container*/
ul {
	align-items: flex-start || flex-end || center || stretch || baseline
}
```

* `stretch` (default): items will fill the container 
* `flex-start / start / self-start`: items are placed at the start of the cross axis
* `flex-end / end / self-end`: items are placed at the end of the cross axis
* `center`: items are centered along the cross-axis
* `baseline`: items are aligned along their baselines

Let’s look at an example of `baseline` below:

```css
ul {
			display: flex;
			border: 1px solid red;
			padding: 0;
			list-style: none;
			justify-content: space-between;
			align-items: baseline;
			min-height: 50%;
			background-color: #e8e8e9;
		}

		li {
		  width: 100px;
		  background-color: #8cacea;
		  margin: 8px;
		}

		/* apply to all list items except the first one*/
		li:not(:first-child) {
			font-size: 2rem;
		}
```

**Output:**

![baseline](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5lzi9969vz14dkwycxn.png)

### align-content

The `align-content` property is used on multi-line flex-containers. It takes the same values as `align-items` (except for `baseline`).

```css
.container {
  align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline + ... safe | unsafe;
}
```

* `normal` (default): items are placed in default position
* `flex-start / start`: items placed to the start of the container
* `flex-end / end`: items placed to the end of the container
* `center`: items are centered 
* `space-between`: items are distributed evenly
* `space-around`: items are evenly distributed, and the first line is at the start of the container with the last at the end
* `space-evenly`: items are evenly distributed with equal space around and between them
* `stretch`: items are stretched to take up remaining space of your container

<br>

<a name="item"></a>


## Flex item properties

Just as our container or parent has its own properties, so do our items. Let's look at the main properties for aligning our flex items.

### order

The `order` property allows you to reorder the flex items. Basically, you can move a `flex-item` from one position to another. The default value for the order property is `0`. It may take on either negative or positive values.

Flex items are re-ordered based on the number values of the order property, from lowest to highest. For example:

```css
.item {
  order: 5; /* default is 0 */
}
```

### flex-grow and flex-shrink

The `flex-grow` and `flex-shrink` properties control how much a flex-item can grow (extend) if there are extra spaces or shrink if there are no extra space. They may take up any values ranging from 0 to any positive number.

For example, if all flex items have `flex-grow` set to `1`, then the remaining space is equally distributed to the other children items. 

> The value `0` is like a “turn-off” switch for this property.

```css
.item {
  flex-grow: 3; /* default 0 */
}
```

```css
.item {
  flex-shrink: 2; /* default 1 */
}
```

### flex basis

The `flex-basis` property specifies the initial size of a `flex-item`, which can be a length (e.g. 20%) or a keyword. For example, the `auto` keyword states that the width or height property is used.

```css
.item {
  flex-basis:  | auto; /* default auto */
}
```

Let's set a `flex-item` to a fixed width:

```css
ul {
			display: flex;
			border: 1px solid red;
			padding: 0;
			list-style: none;
			background-color: #e8e8e9;
		}

li {
			flex-basis: auto;
		  	background-color: #8cacea;
		 	margin: 8px;
		 	min-height: 100px;
		 	color: #fff;
		 	padding: 4px;
		}
```

**Output:**

![Adjusting width in CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1oqa6i6n9568iiuft2j.png)

### flex

The `flex` shorthand allows you set the `flex-grow`, `flex-shrink`, and `flex-basis` properties at once.

```css
li {
  flex: 0 1 auto;
}
```

Here, the code is equal to setting the three properties: `flex-grow: 0`; `flex-shrink: 1`; `flex-basis: auto`.

<br>

### align-self


This property allows you to override the default alignment. For example, you could use it to change the position of a single `flex-item` along the `cross-axis` without affecting the neighboring `flex-items`. It can take these values, which should already be familiar to you:

```css
li:first-of-type {
	align-self: auto || flex-start || flex-end || center || baseline || stretch
}
```

<br>

<a name="next"></a>

## What to learn next

You should now have a solid idea of how to design and align using the flexbox properties. Clearly, flexbox makes your CSS life way easier. Once you master the basics, it will be easier than ever to take charge of your web dev projects. 

There is still more to learn about flexbox. Some good topics to cover next are:
* Absolute and relative flex-items
* Auto-margin alignment
* Responsive design with flexbox

To get started with these advanced topics, check out Educative's learning path **[Become a Frontend Developer.](https://www.educative.io/path/become-front-end-developer?eid=5082902844932096)**  With a curated module on CSS flex-box, this is the ideal place to take your web dev skills to the next level. You will gain a mastery of HTML, CSS, and JavaScript and earn a valuable certificate by the end. 

The skills you gain in this path will give you a valuable leg up on your journey!

*Happy learning!*

<br>

### Continue reading about CSS on Educative
* [Complete Guide to CSS Positions: element layout in CSS](https://www.educative.io/blog/complete-guide-css-positions?eid=5082902844932096)
* [Using Color in CSS: an in-depth guide to CSS color codes](https://www.educative.io/blog/css-color-guide?eid=5082902844932096)
* [Revamp Your Front-End Skills: hands-on with HTML5 and CSS3](https://www.educative.io/blog/revamp-front-end-skills?eid=5082902844932096)

### Start a discussion
What is your personal favorite use of CSS? Was this article helpful? Let us know in the comments below!