Getting Started With CSS Flexbox Using Practical Examples


By

Flexible boxes, or flexbox, is the latest method for controlling layouts in CSS. Using grids that are ‘flexible’ is so easy to predict how each element behaves on different screen sizes.

Its greatest feature is its ability to manipulate an item’s width/height to occupy all the space within its container (also known as a “flex container”) – otherwise, it shrinks to prevent overflow.

Unlike the regular CSS box model, flexbox offers an enhanced model for block elements without the use of floats. And, it supports direction – which means you can control the flow of each item vertically or horizontally. Almost all browsers that are active today support it, so it’s good to know how it can be used on different kinds of projects.

To give you an idea of how amazing flexbox is, I wrote this quick tutorial to show how you can use it on your website. We’ll use flexbox properties and media queries to enable the responsive layout of each element on different screen sizes and show you the advantages of using it on your projects. Let’s get started.

If you’re new to flexbox, you might also like to take a look at these Guides, Tools & Frameworks for getting started with CSS flexbox.



Navigation Bar Using Flexbox

Flexbox is perfect for creating a responsive navigation. You can lay out the navigation in one column on smaller viewports, scale it up on medium size viewports and position it in one row on large and extra-large viewports. Let’s look at how to create a navigation using flexbox.

For the HTML, we will wrap our navigation within a header tag. We will use an unordered list (ul) for our links with their respective classes. Here is the HTML:

<header class="header">
  <h1 class="logo"><a href="#">Flexbox</a></h1>
  <ul class="main-nav">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Portfolio</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</header>

For the CSS, we will first add the basic styles that we need:

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

h2,h3,a {
  color: #34495e;
}

a {
  text-decoration: none;
}

.logo {
  margin: 0;
  font-size: 1.45em;
}

.main-nav {
  margin-top: 5px;
}

.logo a,.main-nav a {
  padding: 10px 15px;
  text-transform: uppercase;
  text-align: center;
  display: block;
}

.main-nav a {
  color: #34495e;
  font-size: .99em;
}

.main-nav a:hover {
  color: #718daa;
}

.header {
  padding-top: .5em;
  padding-bottom: .5em;
  border: 1px solid #a2a2a2;
  background-color: #f4f4f4;
  -webkit-box-shadow: 0 0 14px 0 rgba(0,0,0,0.75);
  -moz-box-shadow: 0 0 14px 0 rgba(0,0,0,0.75);
  box-shadow: 0 0 14px 0 rgba(0,0,0,0.75);
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

When the viewport is 769px or wider, we will use flexbox to change the vertical layout of the navigation to a horizontal layout. That will fill the horizontal space of the large and extra-large screens and devices.

To do that, we will use media queries to manipulate the layout. We will declare the display: flex to set the flexbox on all elements. We will also set the flex-direction: column to set the axis of our element from top to bottom.

@media (min-width: 769px) {
  .header,.main-nav {
    display: flex;
  }

  .header {
    flex-direction: column;
    align-items: center;
    width: 80%;
    margin: 0 auto;
    max-width: 1150px;
  }
}
}

On a screen size with a minimum width of 1025px, we will set the flex-direction: row with justify-content: space-between. This means that our header will be displayed horizontally instead of vertically.

@media (min-width: 1025px) {
  .header {
    flex-direction: row;
    justify-content: space-between;
  }
}

Here is the final output:

See the Pen Flexbox Navigation Bar by Sam Norton

Thumbnail Gallery with Flexbox

Thumbnails are smaller versions of images that are organized in a particular area of a website to give you a hint of how the full-sized picture looks. Usually, thumbnails are used for image galleries. With flexbox, you can create thumbnails using the row property while manipulating the display size of the image.

For our thumbnail example, we will create a div with a class of thumb that will wrap all of our thumbnail images. This will also be our flex container.

<div class="thumb">
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
  <div><img src="https://www.iliveaccountable.com/wp-content/uploads/2016/05/thumb.jpg"></div>
</div>

For our CSS, we will set a width for the flex container, which is the thumb class. We will then set the display to flex to set the flexbox property inside it. There are three properties that we need:

  • flex-wrap – to set our flexible items in a single line or can be flowed into multiple lines. In this case, we use wrap. This means our thumbnails will be set to the multi-lines direction.
  • flex-direction – to specify the direction of the flexible items. In this case, we set it to columns. This means our thumbnails will be displayed from top to bottom.
  • flex-flow – which is a shorthand property for the flex-direction and the flex-wrap.
.thumb { 
  width: 30%;
  margin: 0 auto;
  border: 1px solid #898989;
  padding: .6vw;
  -ms-flex-wrap: wrap;
  -ms-flex-direction: column;
  -webkit-flex-flow: row wrap; 
  flex-flow: row wrap; 
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

Next, we will set the width on our images using the box-flex property to auto. To specify a -moz-box or -webkit-box grows to fill the box that contains it. The rest of the code is simple media queries to manipulate the padding on a viewport with a maximum width of 480px.

.thumb div { 
   width: 100px; 
  margin: .6vw; 
  -webkit-box-flex: auto;
  -ms-flex: auto;
  flex: auto; 
}
.thumb div img { 
   height: auto; 
  width: 100%; 
}
@media screen and (max-width: 480px) {
  .thumb div { margin: 0; }
  .thumb { padding: 0; }
}

Flexbox Forms

A form is a vital part of every website. It enables users to input data using checkboxes, radio buttons, or text fields that are sent to a server for processing. With flexbox, you can create responsive forms without depending too much on media queries.

Let’s first create our text fields and wrap them within a form tag. For our container, we will use a div with a class of form.

<div class="form">
  <form action="#">
    <div>
      <p class="title">Registration Form</p>
      <p><label for="first name">First Name :</label> <input autofocus="" id=
      "first_name" type="text"></p>
      <p><label for="last name">Last name :</label> <input id="last_name" type=
      "last_name"></p>
      <p><label for="email">E-mail :</label> <input id="email" type=
      "email"></p>
      <p><input class="btn" type="submit" value="Register"></p>
    </div>
  </form>
</div>

For our CSS, we’ll add first the basic styles:

form {
  border: 1px solid #555;
  padding: 20px;
  width: 50%;
  box-sizing: border-box;
  margin: 0 auto;
}

.title {
  font-size: 27px;
}

.btn {
  position: relative;
  vertical-align: top;
  height: 40px;
  width: 25%;
  padding: 0;
  font-size: 15px;
  color: #fff;
  text-align: center;
  background: #4d4d4d;
  border: 0;
  border-bottom: 2px solid #d0d0d0;
  cursor: pointer;
  margin-left: auto;
}

label {
  width: 7em;
  margin-right: .5em;
}

Now to make it responsive, let’s add display:flex on the paragraph label tag so that it collapses on smaller screens. We will also add flex: 1 on our input type to enable all of the flexible items on the same length inside the same container. We will then add our media queries for screens with a maximum width of 600px and display the labels of each field as block elements as well as the button element.

input:not([type="submit"]) {
  flex: 1;
  padding: 10px 20px;
  box-sizing: border-box;
}

p {
  display: flex;
}

@media (max-width: 600px) {
  p {
    display: block;
  }

  input {
    width: 100%;
  }

  input[type="submit"] {
    width: 100%;
  }
}

Check the final output below:

See the Pen Flexbox Forms by Sam Norton

Sticky Footer with Flexbox

A sticky footer is a footer that “sticks” to the bottom of the screen no matter how long or short the content of the web page is. While there are several ways to create one, flexbox is a great option.

For our HTML, let’s create a simple web page using the header, section, and footer tags:

<header>
  <h1>A Big Header</h1>
</header>
<section>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<footer>
  <p>© Flexbox Sticky Footer</p>
</footer>

For our CSS, we will set the display: flex property to our body tag to enable flexbox. We will also set the flex-direction column to set the direction of the flex items from top to bottom, along with some basic styles.

body {
  font-family: 'Montserrat',sans-serif;
  line-height: 1.6;
  margin: 0;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

Since we are using the section tag as our container, we will set the flex property to 1. This sets the section content to the same length regardless of its content relative to the rest of the container.

section {
  padding: 10px;
  flex: 1;
}

The rest are just simple styles for our elements.

Check out the demo below:

See the Pen Flexbox Sticky Footer by Sam Norton


The CSS3 Flexible Box is a very helpful feature nowadays. Many web designers and developers find it easier to use on their websites than the typical CSS layout model.


Top
This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.