Learn CSS Flexbox in 5 Minutes

A quick introduction to the popular layout module

I’ve also created a free 12-part course on Flexbox. Check it out here if you’re interested!

Now let’s get started!

Your first Flexbox layout

The two main components of a Flexbox layout are the container and the items.

<nav class="container">
<div>Home</div>
<div>Search</div>
<div>Logout</div>
</nav>
I’ve added a little bit of styling, but that has nothing to do with Flexbox.
.container {
display: flex;
}

Justify content and Align items

Justify-content and align-items are two CSS properties which help us distribute the items in the container. They control how the items are positioned along the main axis and cross axis.

.container {
display: flex;
justify-content: center;
}
.container {
display: flex;
justify-content: space-between;
}
  • flex-end
  • center
  • space-between
  • space-around
  • space-evenly

Controlling a single item

We can also control single items. Let’s say we for example want to keep the first two items on the left side, but move the logout button to the right side.

.logout {
margin-left: auto;
}
.search {
margin-left: auto;
}

The flex property

So far, we’ve only had fixed-width items. But what if we want them to be responsive? To achieve that we have a property called flex. It makes it a lot easier than the old way of using percentages.

.container > div {
flex: 1;
}
.search {
flex: 1;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store