Using Flexbox to Build Flexible Layouts

Using floats in CSS always gave me so much heartache. Floats were always unpredictable, which led to many hacks to get them to behave properly. If our webpage includes responsive resizing, floats took its nuisance to a whole new level.

Flexbox introduces a new way of executing our layouts that makes it easier to write and comprehend.

To get started with flexbox, we first need to declare a flexbox container. The container will have a display property with a value of flex. This will make certain all children elements are recognized as flexbox items.

CSS

    .flexbox-container {
      display: flex;

      /* Optional flex-direction values */
      /* Flexbox items flow horizontally */
      flex-direction: row;

      /* Flexbox items flow vertically */
      flex-direction: column;
    }

HTML

    <section class="flexbox-container">
      <!-- ...content -->
    </section>

Flexbox Items

Flexbox items will be considered children of its parent container. Let's go ahead and insert some flexbox items.

CSS

    .flebox-item {
      flex: 1;
    }
    /* `flex` is the shorthand property of the below  => */
    /* flex-grow: 1; */
    /* flex-shrink: 0; */
    /* flex-basis: auto; */

HTML

    <div class="flexbox-item"></div>
    <div class="flexbox-item"></div>
    <div class="flexbox-item"></div>

Above we use the shorthand property flex for our flexbox items. We then pass it a single value of 1. By passing only one value with no unit indicated, we will set our flex-grow property to be 1 and leave flex-shrink and flex-basis to their browser defaults.

All together now

CSS

    .flexbox-container {
      display: flex;
      height: 100px;
      flex-direction: row;
    }

    .flexbox-item {
      flex: 1;
      padding: 0.5em;
    }

    .flexbox-item:nth-child(1) {
      background: #ccc;
    }

    .flexbox-item:nth-child(2) {
      background: #bbb;
    }

    .flexbox-item:nth-child(3) {
      background: #999;
    }

HTML

    <section class="flexbox-container">
      <div class="flexbox-item"></div>
      <div class="flexbox-item"></div>
      <div class="flexbox-item"></div>
    </section>

Output

flexbox 1
flexbox 2
flexbox 3

Can I Use Flexbox

Can I Use Flexbox

Yes, you sure can!

Up