As I’ve shown previously, flexbox is a powerful CSS layout engine. One of its many advantages is the fact that a horizontal flexbox layout can be displayed vertically with a single line of CSS code, with elements rearranged in any order you wish. This makes flexbox perfectly suited to modern responsive design, where layouts are commonly re-oriented for smaller screens. In this article I’ll look at more of the powerful options this creates for designers.
Let’s take a simple arrangement of shapes:
<<figure id="flex">
<div id="triangle"></div>
<div id="square"></div>
<div id="circle"></div>
</figure><figure>
Shaped with the following CSS:
#flex {
display: flex;
padding: 2rem;
}
#triangle {
width: 0; height: 0;
border-bottom: 114px solid hsl(240, 30%, 50%);
border-left: 63px solid transparent;
border-right: 63px solid transparent;
}
#square-vert {
width: 126px; height: 126px;
background: hsl(300, 30%, 50%);
}
#circle-vert {
width: 126px; height: 126px;
border-radius: 50%;
background: hsl(340, 30%, 50%);
}
By default, the elements are arranged along a horizontal axis. To change that, we just need a simple declaration:
#flex { flex-direction: column; }
…which produces the display you can see at the left in the banner image.
Note that the elements are arranged “top down” by default, and aligned to the left. All the properties I discussed in the previous article can be applied here: it’s just that the context is now vertical, rather than horizontal.
Placing the elements at the “end” of the flexbox container is easy, so long as the container itself is tall enough to show visible realignment of its children. At the same time, we can align the elements horizontally and reverse their order:
#flex {
height: 500px;
justify-content: flex-end;
flex-direction: column-reverse;
align-items: center;
}
…which produces the stack to the right.
Combining both horizontal and vertical flexbox alignment finally provides web designers with true, honest-to-goodness perfect centering of elements, one of the techniques shown in my “Seven Ways To Center With CSS” article.
Basic Flexbox For Mobile
Switching a layout between larger and smaller screens becomes very easy with flexbox. Given this pseudo-code:
<header></header>
<div id="wrapper">
<nav></nav>
<main></main>
</div>
<footer></footer>
We can switch the arrangement of the <nav>
and <main>
elements between side-by-side:
div#wrapper { display: flex; }
To one above the other at smaller viewport sizes:
@media (max-width: 400px;) {
div#wrapper {
flex-direction: column;
}
}
There’s much more that we can do with flexbox, as I’ll show in upcoming articles.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.