Using Flex Box For Responsive Design

Using Flex Box For Responsive Design

Flex Box is Pretty Awesome

Today I’m going to show you how to use Flex Box to create a row of buttons that turns into a responsive list of links with just CSS. This technique can be useful for having multiple large calls to action. Keep reading to learn what’s going on in the code, or just jump to the bottom for the source code, it’s up to you.

Flex-Grid

Basic HTML

We’ll start off with some initial markup:

<container>
    <div class="button">
        <p>Classes</p>
    </div>
    <div class="button">
        <p>Instructors</p>
    </div>
    <div class="button">
        <p>Sign&nbsp;Up</p>
    </div>
</container>

Desktop CSS

Then we’ll add some CSS to make the Desktop version:

desktop css
container {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 70%;
    flex-wrap: wrap;
}

.button {
    background: rgba(255, 255, 255, 1);
    width: 15%;
    text-align: center;
    height: auto;
}

What this does is makes the container the Flex Box for all the buttons. We can then use all of the flex box properties to adjust how the buttons display. For more info on flex box and what you can do with it, check out CSS-Trick’s Comprehensive Guide.

Mobile CSS

Now for the magic. By adding the cards and the container to the mobile media query we can then manipulate the flex-direction property. As you can guess, flex direction adjusts which way the items will flow inside the container. By setting the container to flex-direction: column, and the cards to flex-direction:row; we can layout the buttons in a much more mobile friendly way.

mobile css
@media screen and (max-width: 900px) {
  container {
    flex-direction: column;
  }

  .button {
    width: 100%;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 0.5em;
  }
  .button p {
    padding: 0 0.5em;
  }

}

That's it! With a little flex box magic and a single media query you can easily have a row of buttons for your users with more screen real estate, and a column for those on their phones and small tablets.

See the Pen ROW TO COLUMN by Jack Harner (@jackharner) on CodePen.