Creating Responsive Layouts with Flexbox

You can build highly responsive website designs using CSS Flexbox. By combining the display property with CSS media queries, you can easily change how elements are positioned on small screens.

Flexbox (Flexible Box Layout Module) was designed specifically to help you align elements and distribute space within a container, even when the size of your elements is unknown or dynamic. This makes it a perfect tool for responsive web design.

Establishing the Flex Container

To start using Flexbox, you must define an outer container as a flex container. Any direct children of this container will immediately become "flex items". We do this by applying display: flex; to the parent container:

The parent container can be a div if there's no semantic HTML element to use, but it can also be any of the more semantic HTML elements, such as a header, nav, main, footer, or section.

Making it Responsive: Changing Direction

While flex-direction: row may look great on desktop computers, side-by-side columns usually get too squished on a mobile phone. The easiest way to make a Flexbox layout responsive is to use a media query to change the flex-direction to column when the screen becomes narrow:

The Flex Wrap Approach

Another approach is to allow your items to wrap onto the next line if they run out of space. By using the flex-wrap property, items will naturally fall into a new row on smaller screens without needing explicit media queries in some cases:

Full Working Example

This layout uses the flex-direction method. Try viewing this example on a mobile device or resizing your browser to see the three columns stack perfectly on top of each other:

View Output Full Screen Preview