Updated 1 day ago | GitHub
On this page

Flexbox

What is Responsive Web Design

Responsive web design (RWD) is a development approach that allows for elements to dynamically change their appearance or layout depending on screen size. For example, elements may reorder, grow/shrink in size depending on the size of the screen. There are different methods for incorporating responsive design. On this page we will explore a tool called Flexbox that helps create a fluid layout for website responsiveness, ending with a layout that changes with the screen width. To learn more about other methods, check out MDN Doc on responsive design.

Flexbox at a Glance

Flexbox (or Flexible Box) creates a flexible container around items. It is an efficient way to position, align, and distribute items that are responsive to screen size. When discussing the Flexbox Layout, we will identify two key terms: flex container and flex items.

+--------------------- flex container ---------------------+
|                                                          |
|    +--------+      +--------+      +--------+            |
|    |  item  |      |  item  |      |  item  |            |
|    +--------+      +--------+      +--------+            |
|                                                          |
+----------------------------------------------------------+
  • Flex container: This is a container or grouping of items. Properties for the container include organizing the direction, wrap, distribution, and alignment of the items contained in the flex container.
  • Flex item: This refers to the elements contained in the flex container. Properties for the items include the order of items, changes in size based on screen size, and self alignment compared to other items.

Creating a Flexbox container and items

You may be wondering, how do we even define or create a Flexbox container and items? Typically developers use the div HTML element to create sections that will be then defined as a Flexbox. In the CSS style file, we add a rule for these div containers that sets the property display to the value flex.

.container{
	display: flex;
}

In the example above, we create a rule that any element with the class name container will have the display property with value flex (aka a Flexbox!). Note that a class selector matches elements by their class attribute regardless of tag — we typically apply it to div elements, but the rule itself isn’t limited to them. Once you have defined a flex container, its direct children automatically act as flex items. Elements nested deeper inside those children do not become flex items of this container (per MDN’s flexbox basic concepts, “the direct children of that container become flex items”), though a flex item can itself be given display: flex to lay out its own children.

The main axis and the cross axis

Flexbox lays items out along two axes. The main axis is set by the flex-direction property, and the cross axis runs perpendicular to it. With flex-direction: row (the default) the main axis runs along the row and the cross axis runs down the columns; with flex-direction: column the main axis runs from the top of the page to the bottom and the cross axis runs along the rows (MDN: Basic concepts of flexbox). The alignment properties below are described in terms of these two axes, so it helps to know which way the main axis is running.

Just setting display: flex gives you these defaults, per the same MDN guide:

  • Items display in a row (flex-direction defaults to row).
  • Items start from the start edge of the main axis.
  • Items do not grow along the main axis, but they can shrink.
  • Items stretch to fill the cross axis (align-items defaults to stretch).
  • Items stay on a single line (flex-wrap defaults to nowrap) and overflow the container if they don’t fit.

Flex container properties

These properties go on the flex container (the element with display: flex) and affect all of its flex items:

Property What it controls Common values (default first)
flex-direction The direction of the main axis row, row-reverse, column, column-reverse
flex-wrap Whether items can move onto a new line when they don’t fit nowrap, wrap
flex-flow Shorthand for flex-direction followed by flex-wrap for example row wrap
justify-content How items and the space between them are distributed along the main axis flex-start, flex-end, center, space-between, space-around, space-evenly
align-items How items are aligned on the cross axis stretch, flex-start, flex-end, center, baseline
.container {
  display: flex;
  flex-flow: row wrap;            /* same as flex-direction: row; flex-wrap: wrap; */
  justify-content: space-between; /* spread the items out along the main axis */
  align-items: center;            /* center the items on the cross axis */
}

The -reverse values of flex-direction keep the same axis but switch its start and end lines, so the items display in the opposite order (MDN: Basic concepts of flexbox).

Flex item properties

These properties go on the individual flex items:

  • order changes where an item appears. Items are sorted by ascending order value and then by their source order, and items without an explicit order get 0 (MDN: order). It only changes the visual order, not the DOM order that screen readers and keyboard navigation follow, so avoid using it to reorder content whose meaning depends on its order.
  • flex-grow, flex-shrink and flex-basis control how an item’s size changes as the container gets bigger or smaller. flex-basis is the item’s starting size on the main axis (default auto, which uses the item’s own size or its content’s size); flex-grow lets the item grow into available space (default 0); and flex-shrink lets it shrink below its flex-basis when space runs out (default 1) (MDN: Basic concepts of flexbox).
  • flex is the shorthand for all three, in the order flex-grow, flex-shrink, flex-basis. The values you’ll see most often are flex: 1 (which expands to flex: 1 1 0%), flex: auto (1 1 auto), flex: none (0 0 auto, a fully inflexible item) and flex: initial (0 1 auto, the defaults) (MDN: flex). Note that the 0% basis from flex: 1 is a percentage, not the same as writing an explicit 0: a percentage flex-basis is resolved against the flex container, and if the container’s size is indefinite (for example a flex-direction: column container with no set height) it is treated as content, whereas 0 always starts the item at zero size (MDN: flex-basis).
  • align-self aligns a single item on the cross axis, overriding the container’s align-items for that item only, with values such as flex-start, center or stretch.
.sidebar {
  flex: 1;                /* expands to flex: 1 1 0% */
}

.main {
  flex: 2;                /* expands to flex: 2 1 0%; grows twice as much as .sidebar */
}

.badge {
  order: -1;              /* displayed before items that keep the default order of 0 */
  align-self: flex-start; /* sits at the cross-axis start even if the container centers its items */
}

Putting it together: a responsive layout

Flexbox becomes responsive when you combine it with a media query, which applies CSS only when a test such as “the viewport is at least 600px wide” passes. A common approach, called mobile first, is to start with a simple single-column layout for narrow screens and switch to a multi-column layout only when there is enough width (MDN: Responsive design). This example, adapted from that MDN article, does exactly that:

<div class="wrapper">
  <div class="col1">Sidebar</div>
  <div class="col2">Main content</div>
</div>
@media screen and (width >= 600px) {
  .wrapper {
    display: flex;
  }

  .col1 {
    flex: 1;
    margin-right: 5%;
  }

  .col2 {
    flex: 2;
  }
}

Below 600px the .wrapper is not a flex container, so the two divs stack in a single column. Once the viewport is at least 600px wide, .wrapper becomes a flex container and the columns sit side by side, with .col2 growing twice as much as .col1. Resize your browser window across the 600px width to watch the layout switch. The (width >= 600px) test is the range-syntax form of (min-width: 600px); MDN documents both forms as interchangeable (MDN: Using media queries).