There are several ways to implement gutters between items in flexible layouts, each with their own set of hacks. In this post I want to share a simple technique I’ve been using to much success, which I’ll refer to as “sliced padding”.
To demonstrate this technique, we’ll use an example.
Given the following wireframe for a button with an icon and some text, how should we implement the gutter between the icon and text? We’ll say the padding of the button is 1 unit, and the gutter is ½ units. When forced to shrink in size, the button can wrap its contents.
Layout is trivial thanks to flexbox.
display: flexenables flexbox.
flex-wrap: wrapenables wrapping of the flex items (button icon and text) when the parent (button) element can no longer contain all flex items on a single line.
justify-content: centercenters the flex items on the X axis.
We can’t use single direction margins because the exact location of the gutter is unknown as the component is designed to be flexible. When exactly we switch from vertical layout to horizontal or vice versa is unknown, because it depends on the component’s contents and its surrounding environment on the page. There’s no way to use media queries to solve this problem.
We could apply single direction margins along two axis (e.g. right for X and bottom for Y), but this would require negative margin hacks on the container element, meaning we can no longer apply useful margins without additional wrapping of elements.
A simple solution to this is to slice and compose our padding unit, letting maths take care of how much spacing to apply between items for all layout permutations.
If we give the button padding of ¾ units and wrap the button’s icon and text with ¼ units of padding, the button’s contents will appear to have the correct padding of ¾ + ¼ = 1 unit. The button’s icon and text each have ¼ units of padding, so when sitting together—horizontally and/or vertically—the gutter between these elements will appear as desired, because ¼ + ¼ = ½ units.
I’ve found the sliced padding technique to scale nicely for all of my spacing requirements. Below are some more examples demonstrating this technique.
The page below has three examples of this technique in action: button with icon, group of buttons, and form layout. To demonstrate flexibility, each example has full and short width variants.