Historically, a major shortcoming of CSS has been its lack of a simple, streamlined layout mechanism. When developing a page layout of any significant complexity , the CSS can quickly devolve into endless spaghetti of “float”s and “clear”s, and hackish, ugly mechanisms like negative margins. And the developer in question had better pray that he or she is working with some fixed-sized elements, lest there be no concrete reference point for anything on the page, and things become even more of a convoluted nightmare. In short, arranging elements in a reliable and fluid manner has been a notoriously painful task.
Thankfully, many of these concerns have been remedied with the introduction of the CSS flexbox (flexible box) model. The flexbox model is specifically designed to build scalable, fluid layouts using a straightforward, intuitive system. It is supported by all major modern browsers (even IE!), and it takes little time to learn/understand.
I will explain some of the fundamentals of the flexbox system. The flexbox layout is initiated by using the following rule on a parent container:
Important Note: Like many new CSS features, the “-webkit-“, “-moz-“, and “-ie-” prefixes need to be used with some versions of Webkit, Firefox, and Internet Explorer browsers, respectively. Refer to the CanIUse page for more details.
Unlike block or inline layouts, the elements within a flex container do not have to be given explicit rules to define their orientation and size in relation to one another, or in relation to their parent container. The benefit of the flex system is that the elements will automatically be sized / positioned relative to their parent. Some things to know about flexbox:
- Floats do not apply to items in a flexbox layout.
- Clears do not apply to items in a flexbox layout.
- Vertical aligns do not apply to items in a flexbox layout.
With the flexbox model, some of the most headache-inducing features of CSS are eliminated entirely! Want to align something dead center (horizontally and vertically) in its parent? Just set on the child:
Want to “float” it to the right? Set on the child:
and on the parent:
justify-content:flex-end; flex-direction:row; align-items:center;
Want if you want the content to be spaced evenly to fill its parent container? Just make the following change to the previous rules:
You can also specify the direction that the content will flow (i.e. horizontally or vertically) with the flex-direction rule. The following makes content flow vertically:
These are just some of the many options available in the flexbox model. I’ve only scratched the surface of its power, but it’s already made my web development experience a whole lot more enjoyable.