Safari 14.1 (April 2021) added support for the gap
property to be used with Flexbox as well as Grid, but lots of users will still be on older versions of Safari if they have been putting off upgrading their Mac or iOS device.
Here's a small TailwindCSS plugin that adds a new set of flex-gap
utilities (and an optional flex-gap-wrapper
class) to use a negative margins hack to emulate gap
in older browsers.
The plugin was based on this Github comment and this example that I found via Twitter. There is also the benface/tailwindcss-gap plugin, but it currently lacks support for Tailwind 2.
Here's an example of my little plugin in use:
<div class="flex-gap-wrapper">
<div class="flex flex-wrap flex-gap-4">
<div>Item one</div>
<div>Item two</div>
<div>Item three</div>
</div>
</div>
The flex-gap-wrapper
element is optional but can prevent issues with overflowing background colours.
Here's the plugin code:
plugin(({ addUtilities, e, theme, variants }) => {
addUtilities({
'.flex-gap-wrapper': {
overflow: 'auto',
},
// This bit might need some work if you use a custo,
// prefix. See https://tailwindcss.com/docs/plugins#manually-prefixing-selectors
// for more info on manual prefixing complex selectors.
'[class*="flex-gap-"]:not([class*="flex-gap-wrapper"])': {
margin: 'calc(-1 * var(--gap)) 0 0 calc(-1 * var(--gap))',
'& > *': {
margin: 'calc(var(--gap)) 0 0 calc(var(--gap))',
},
},
});
Object.entries(theme('gap')).forEach(([key, value]) => {
addUtilities(
{
[`.flex-gap-${e(key)}`]: {
'--gap': value,
},
},
variants('gap'),
);
});
}),
Top comments (0)