Flexbox

A new way to layout elements

Flexbox is a layout model that allows you to design complex layouts with a single container element and its children. It's a powerful tool that makes it easier to create responsive designs and align elements in a predictable way.

Basic usage

To use Flexbox, you need to define a display: flex; property on the parent container. This will turn the container into a flex container and allow you to use flex properties to control the layout of its children.

<!-- HTML -->
<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

/* CSS */
.container {
  display: flex;
}

Flex properties for the container

There are several properties you can use to control the layout of the flex container:

Here's a demo showing a typical flexbox use case of a navigation bar:

<!-- HTML -->
<nav class="navbar">
  <svg>...</svg>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Contact</a>
</nav>

/* CSS */
.navbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 0.25rem;
}

Flex properties for the children

There are also properties you can use to control the layout of the flex items:

Here's an example using the order property to move the second item to the beginning:

<!-- HTML -->
<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

/* CSS */
.container {
  display: flex;
}

.item:nth-of-type(2) {
  order: -1;
}
Item 1
Item 2
Item 3

Here's an example using the flex-grow property to make the first item grow to fill the available space:

.item:first-of-type {
  flex-grow: 1;
}
Item 1
Item 2
Item 3

As a shorthand, you can use the flex property to set the flex-grow, flex-shrink, and flex-basis values at once. Some examples:

.item {
  flex: 1;
}
Item 1
Item 2
Item 3

A few different nav examples

Here are a few different examples of navigation bars using flexbox. Use your browser's dev tools to inspect the elements and see how they work.

Flexbox Demos

Resources