Flex-Cheat — Easy Cheat Classes for Varied CSS Layouts Using Flexboxes
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 a
display:flexand all it's immediate children as fixed width i.e. both flex-grow and flex-shrink set to 0.
flex-containerbut sets display to
flex-container+ centers direct child elements using
flex-container.column+ centers direct child elements using
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 as
flex-restthey share remaining space equally. Components marked
flex-restwill 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:
I’d love to hear your opinion on things I’ve written in this article, so do chime in with your comments below.
Originally published at asleepysamurai.com on January 29, 2019.