CSS Flexbox

By Tony 8.15.2024


Sure, you can position several elements using padding and margin, or even the <br> tag. But is it efficient? Does it really achieve the layout you want? Is it flexible enough? CSS flexbox is all three of these. It's efficient, powerful, and flexible at laying out elements.

display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
flex-wrap: wrap;

To make all these properties work, you need to set the display of the container of the elements to display: flex; To understand how flexbox works, first imagine three elements being attached to an axis. The flex-direction property specifies whether the axis is horizontal or vertical. The property justify-content tells the browser how to position the three elements along the axis. It can be at the center of the axis, at the start/end of it, or equally spaced out from each other. Now imagine there's some space around the axis, forming a box (flexbox). align-items determines where the axis should be aligned. At the beginning edge of the box, the center of the box, or the end of the box. Note that align-items moves the axis itself, and justify-content moves the elements along the axis. Well, what if there's too many elements and the axis is full? The flex-wrap property tells the browser to create a new axis directly after (and parallel) the original axis and put the extra elements on it if the original axis is full.

HTML
CSS
JavaScript
Output

As you can see above, the elements are being aligned in the center (horizontally and vertically) of the orange container without any margin or padding thanks to the justify‑content and align-items properties. And because of flex-wrap: wrap; element 4 is being wrapped to a new line (axis), and not overflowing the orange container. Although there is a ton more properties, values, and techniques related to flexbox, these are the major ones you'll use the most often, so play around with the values and properties and see what happens!

Summary

CSS flexbox is a very powerful tool for laying out elements. display: flex turns a container into a flexbox, justify-content positions the elements within the container along an axis, and align-items positions the axis within the container. flex-wrap wraps overflowing elements into a new axis and flex-direction changes the direction on the axis. To put the axis analogy into the real world of flexbox, the box containing the axes is the HTML element that contains the elements you want to layout. The objects on the axis are the elements in the container box, or flexbox, that you want to lay out.

We know we covered a lot in this tutorial, but if you take the time to understand, learn, and actually try flexbox out, you'll find that it is incredibly powerful and useful. From simply aligning something to the center or making the elements line up in a row, to creating interactive cards and buttons, flexbox's usage is everywhere. Have fun 🔥!