Flexbox

Introduction to Flexbox

Flexbox is an amazing tool for website layout.

It alleviates many issues that have existed since the beginning of CSS.

Flexbox helps to accomplish the following:

Notes to Remember

The Flex Container

Flexbox works by applying CSS properties to both the container, and the children inside the container.

Example

 .container {
  display: flex;
  flex-direction: row;
}

Illustration of Flex Container

Reversing the Order

Example

#container {
  display: flex;
  flex-direction: column-reverse;
}

Illustration of Flex Reverse

Justify Content

Justifying your content, both horizontally and vertically, used to be a very large pain in the neck.

Not anymore! Flexbox makes this easy, with one simple line of CSS. There are 5 different values for the CSS property justify-content:

  1. Flex-start
  2. Flex-end
  3. Center
  4. Space-between
  5. Space-around

Example For Centering Content

#container {
  display: flex;
  justify-content: center;
}

Justifying content with Flexbox

Align Items

align-items is also applied to the flex container. This is similar to justify content, but works along the cross-axis. If your items are arranged in a row, this would act on the vertical axis.

  1. flex-start
  2. flex-end
  3. center
  4. stretch
  5. baseline

Example

#container {
  display: flex;
  align-items: stretch;
}

Flexbox Align Items Property

Flex Direction

Example

#container {
  display: flex;
  flex-direction: row;
}

Flexbox Direction Property

NOTE: if you want your items to be columns, use flex-direction: row in the container, and if you want rows, use flex-direction: column in the container

Controlling Individual Flex Items

Order

Want to switch the first two navigation items on your website? First the container must have the property display: flex;.

Then give the first item order: 2, and the second item order: 1.

(Note that the default value is 0, so all items will need to be given an order number.)

Example

.firstItem {
  display: flex;
  order: 1;
}

.secondItem {
  display: flex;
  order: 2;
}

This is ground breaking. Never before were we able to rearrange the order of elements on a website with pure CSS.

Align Self

  1. flex-start
  2. flex-end
  3. center
  4. stretch
  5. baseline

Example

.navigationBarItem0 {
  display: flex;
  align-self: flex-start;
}

Flexbox Align Self Property

Flexi-grid

Q: What do you get when you put a Flexbox inside a Flexbox?

A: A grid! (But not CSS Grid)

flex-grid

<div class='two-columns'>
  <div class='column'>
    <h2>Meats</h2>
    <div>Turkey</div>
    <div>Ham</div>
  </div>
  <div class='column'>
    <h2>Cheeses</h2>
    <div>Cheddar</div>
    <div>Swiss</div>
    <div>American</div>
  </div>
</div>

<style>
.two-columns {
    display: flex;
    flex-direction: row;
}

.column {
    display: flex;
    flex-direction: column;
}
</style>

 Previous Lesson Next Lesson 

Outline

[menu]

/