Using CSS Flexbox in Responsive Design

Getting elements of a page to collapse responsively is usually fairly simple. When you need different sections of a page to collapse in an order that’s different from the way they’re ordered in the code, however, things can get complicated. For example, let’s say you have a page where the main content is split up into three sections — left sidebar, content, and right sidebar — and let’s say that the left sidebar is an ad. The hierarchy of the code would put the ad at the top of the page when it’s viewed on a mobile device or tablet, with the main content falling underneath the left sidebar, and the right sidebar settling at the very bottom. But what if you don’t want an ad to be the first thing your users see? CSS flexbox seems to be a simple solution.

CSS flexbox is a layout mode that allows, among other things, elements within a container to assume a certain position relative to each other. In other words, you can easily have your divs appear in any order you like, regardless of where they are in the code. With flexbox, it would only take a few lines of CSS to make that left sidebar appear at the very bottom of its container when the page is viewed on a smaller screen.

Join us in our newest publication:

Here’s how it works: give your container a

display: flex

This enables all of the children of this container to behave flexibly — all you have to do is assign them an order. Items within the flex container simply need to be given a number that designates the order in which they should appear on the page. In the case of the left sidebar that’s meant to appear as the 3rd element in the container when viewed on a smaller screen, it would have the property of

order: 3

within a media query. It’s not even necessary to assign numbers to the other two divs, unless you want them to display differently from their default order.

Changing the order of html elements is just one example of the variety of tasks of which flexbox is capable. It can also be used to define spacing between elements, define the size of elements in proportion to one another, and to define the alignment of elements. As responsive design continues to take over the web, CSS flexbox is a worthy tool to have at your disposal.

Share and Enjoy !

0Shares
0 0