Skip to content

Instantly share code, notes, and snippets.

@mpalpha
Last active June 23, 2021 17:02
Show Gist options
  • Save mpalpha/2436946a40bceef8ff0c8dc2373771b8 to your computer and use it in GitHub Desktop.
Save mpalpha/2436946a40bceef8ff0c8dc2373771b8 to your computer and use it in GitHub Desktop.
tailwind plugin to add border padding utilities.
// Inherits padding and border settings from your tailwind config to provide alternate padding utilities,
// which account for border sizes using the css calc() function.
//
// Usage: <div class="abds-pt-2-border-2" = "padding-top: calc(0.5rem - 2px);"
const _ = require('lodash');
const { borderWidth } = require('tailwindcss/defaultTheme');
module.exports = function () {
return function ({ addUtilities, e, config }) {
const paddings = config('theme.paddingBorder.padding', config('theme.padding', {}));
const borderWidths = config('theme.borderWidth', {});
const variants = config('variants.paddingBorder', config('variants.padding', {}));
const prefix = 'border';
const generators = [
(size, modifier) =>
Object.entries(borderWidths).map(([borderKey, borderValue]) => {
let suffix = borderKey.toLowerCase() == 'default' ? '' : `-${borderKey}`;
return {
[`.${e(`p-${modifier}-${prefix}${suffix}`)}`]: { padding: `calc(${size} - ${borderValue})` },
[`.${e(`py-${modifier}-${prefix}${suffix}`)}`]: {
'padding-top': `calc(${size} - ${borderValue})`,
'padding-bottom': `calc(${size} - ${borderValue})`
},
[`.${e(`px-${modifier}-${prefix}${suffix}`)}`]: {
'padding-left': `calc(${size} - ${borderValue})`,
'padding-right': `calc(${size} - ${borderValue})`
},
[`.${e(`pt-${modifier}-${prefix}${suffix}`)}`]: { 'padding-top': `calc(${size} - ${borderValue})` },
[`.${e(`pr-${modifier}-${prefix}${suffix}`)}`]: { 'padding-right': `calc(${size} - ${borderValue})` },
[`.${e(`pb-${modifier}-${prefix}${suffix}`)}`]: { 'padding-bottom': `calc(${size} - ${borderValue})` },
[`.${e(`pl-${modifier}-${prefix}${suffix}`)}`]: { 'padding-left': `calc(${size} - ${borderValue})` }
};
})
];
const utilities = _.flatMap(generators, (generator) => {
return _.flatMap(paddings, generator);
});
addUtilities(utilities, variants);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment