Flex-Cheat is thirty lines of CSS, exposed as six classes, which can be mixed and matched to produce pretty much any HTML element layout using the magic of flexboxes.
In a recent post on HackerNews, a lot of commentators lamented the difficulty of laying out HTML elements using CSS. I used to find laying elements out in HTML using CSS quite annoying and tedious too – until flexbox
came along, and made life a lot easier, at least when it comes to layouts.
For the past few years, I've used the same six custom classes and their associated CSS style declarations, as a layout helper for my applications. By mixing and matching these classes, I've been able to generate pretty much any layout I've wanted to, with minimal pain.
The flex-cheat utility declares the following styles:
flex-container
: Marks an item as adisplay:flex
and all it's immediate children as fixed width i.e. both flex-grow and flex-shrink set to 0.flex-container.column
:flex-container
+ setsflex-direction
to column.flex-container.inline
:flex-container
but sets display toflex-inline
instead offlex
.flex-container.center
:flex-container
+ centers direct child elements usingalign-items
.flex-container.column.center
:flex-container.column
+ centers direct child elements usingjustify-content
.flex-rest
: To be added to specific direct child elements, to allow them to take up the rest of available space. When multiple child elements are marked asflex-rest
they share remaining space equally. Components markedflex-rest
will grow and shrink as required.
The flex-cheat CSS utility, is basically my little magic wand, and waving it just the right way, gives me the exact layout I want. To demonstrate my point, I'm going to show a few different layouts that were generated using only the six flex-cheat classes.
- Fixed Width Row:
- Equal Width Row:
- Mixed Width Row:
- Centered With Fixed Width Row:
- Centered With Mixed Width Row:
- Fixed Height Column:
- Equal Height Column:
- Mixed Height Column:
- Centered With Fixed Height Column:
- Centered With Mixed Height Column:
- Grid With Mixed Rows and Columns:
The HackerNews post, triggered me to clean up the flex-cheat CSS and open source it. You can checkout the flex-cheat CSS utility on Github. Usage examples are available in the examples directory.
I'd love to hear your opinion on things I've written in this article. Unfortunately, I've not yet found a nice lightweight comments widget to add on to my blog, so until then the only way I can take comments is via email. Do write to me at asleepysamurai at google's mail service.