Flexbox Examples

All of the following examples are based on the following HTML:

    <div id="container1" class="container">
      <div class="item">Barry</div>
      <div class="item">Robin</div>
      <div class="item">Maurice</div>
      <div class="item">Leslie</div>
    </div>
    

Note that the outer div has both an ID and a class. The class allows all the outer divs to have some consistent CSS, namely border, padding and margin. The inner divs also have a class, which applies margins, border and padding to each. Here's the consistent CSS:

      .container {
          border: 2px solid green;
          padding: 2px;
          margin: 10px;
      }
      .item {
          margin: 2px;
          border: 2px solid brown;
          padding: 1em;
      }
      

The only thing that will change from example to example is the ID of the container, and the flexbox CSS.

You are also encouraged to "view source" on this page or inspect the elements of each example to see the rules and CSS properties that are applied.

Example: Items can Grow

In this first example, the items are arranged in a row. They have a set width, but they are allowed to grow if the container has extra space.

Note the use of a descendant selector for the flex items.

Barry
Robin
Maurice
Leslie

Example: Items cannot Grow

Here, we set flex-grow: 0 (via the flex shorthand) and so the items stay at their specified widths, even if there is extra space.

Barry
Robin
Maurice
Leslie

Example: First item can Grow

Here, we set flex-grow: 0 on all of them, but override that to allow the first to grow. So it gets all the extra space, if any.

Barry
Robin
Maurice
Leslie

Example: space-between

Here, we set a policy that any extra space is put between items, rather than at the end.

Barry
Robin
Maurice
Leslie

Example: center

Here, we set a policy that any extra space is split between before and after the items, centering them.

Barry
Robin
Maurice
Leslie

Example: space-around

Here, we set a policy that any extra space is evenly divided between and around the items

Barry
Robin
Maurice
Leslie

Controls

Click this button to change the flex-direction to column (instead of row).