Skip to content

Intro to Flexbox

Set up a flexbox container

  • Lesson
  • 2 min read
  • 1 of 5 in this chapter

Flexbox

CSS Flexbox is a layout tool. It's useful to create rows and columns of elements, and to align elements on a page. It can sometimes be used for the same purposes as the CSS grid, but it's more flexible, because it works well even if the exact number/size of the items inside is unknown or changing.

We'll use the same HTML for this lesson as we did for the grid lessons:

HTML
<div class="container">
  <div class="item" id="one">Item 1</div>
  <div class="item" id="two">Item 2</div>
  <div class="item" id="three">Item 3</div>
  <div class="item" id="four">Item 4</div>
  <div class="item" id="five">Item 5</div>
  <div class="item" id="six">Item 6</div>
</div>

We'll also keep the same original CSS as we had at the beginning of the grid lessons, with the exception of the display property. To use flexbox, we have to set the display property of the container to flex (or you can set it to flex-inline for an inline container instead of a block-level one).

CSS
.container {
    display: flex;
    border: 3px solid #ff5376;
  }
.item {
    background-color: #fee440;
    border: 1px solid #ff9505;
}

Flex-direction

This property allows us to create rows and columns with flexbox, and it's applied to the container. The default value of flex-direction is row. The other possible values for it are column (stacks the items vertically), reverse-row (row, but the items are in reverse order), and reverse-column (reverse order column).

CSS
.container {
    display: flex;
    border: 3px solid #ff5376;

    flex-direction: column;
}