Working With Flex

Flexbox (or flex layout) is a CSS box model optimized for user interface design. The child elements of a flex container have greater “flexibility” on how it is laid out on an HTML page. This means that it provides a simpler and more powerful tool for distributing space and aligning content for complex (or simple) layouts in web apps or web pages.

Using Flexbox can get your Responsive website layout working as intended.

Below is the barebones to get Flexbox going. The example is keeping the “Mobile First” approach.

View Demo

The following is a barebones example of the HTML:

1
2
3
4
5
6
<div class="flex--products">
  <div class="product">Product 1</div>
  <div class="product">Product 2</div>
  <div class="product">Product 3</div>
  <div class="product">Product 4</div>
</div>

First we define display: flex to the parent element that we want to hold the elements that will flex.

1
2
3
4
.flex--products {
  display: flex;
  flex-direction: row;
}

flex-direction: row will place each child element on its own row.

For wider viewports, we will switch the elements to be in its each column.

1
2
3
4
5
@media screen and (max-width: 46rem) {
  .flex--products {
    flex-direction: column;
  }
}

For the child elements, we define a flex: auto. flex: auto will automatically adjust the widths of the adjacent elements.

1
2
3
4
5
6
.product {
  flex: auto;
  padding: 1rem;
  margin: .1rem;
  background: $product-color;
}

Full SCSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$midnight-blue: #2c3e50;
$belize-blue: #2980b9;
$white: #fff;

$bg-color: $midnight-blue;
$product-color: $belize-blue;

body {
  background: $bg-color;
  color: $white;
  padding: .5rem;
}

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

.product {
  flex: auto;
  padding: 1rem;
  margin: .1rem;
  background: $product-color;
}

@media screen and (max-width: 46rem) {
  .flex--products {
    flex-direction: column;
  }
}

Below you will find more Flexbox resources:

Reading

Code

Sandboxes

Technical