Skip to content

Instantly share code, notes, and snippets.

@delucis
Created March 26, 2021 17:04
Show Gist options
  • Save delucis/fe296e3e2a0be91e55367e9f648e02f9 to your computer and use it in GitHub Desktop.
Save delucis/fe296e3e2a0be91e55367e9f648e02f9 to your computer and use it in GitHub Desktop.
TailwindCSS Bevelled Corners Plugin
const plugin = require('tailwindcss/plugin');
const BevelPlugin = plugin(function bevelPlugin({ addUtilities, e }) {
const base = 0.5;
const absoluteSizes = Object.entries({
md: 1.5,
lg: 2,
xl: 3,
'2xl': 4,
'3xl': 6,
}).reduce((sizes, [size, scale]) => {
sizes[`.bevel-${size}`] = { '--bevel': `${base * scale}rem` };
return sizes;
}, {});
const relativeSizes = Object.entries({
'1/2': 50,
'1/3': 33.3333,
'1/4': 25,
}).reduce((sizes, [size, percent]) => {
sizes[`.${e(`bevel-${size}`)}`] = { '--bevel': `${percent}%` };
return sizes;
}, {});
const y = ['t', 'b'];
const x = ['l', 'r'];
const corners = {};
// .bevel-t and .bevel-b
for (const ySide of y) {
const flags = {};
for (const xSide of x) {
flags[`--bevel-${ySide}${xSide}`] = '1';
}
corners[`.bevel-${ySide}`] = flags;
}
// .bevel-l and .bevel-r
for (const xSide of x) {
const flags = {};
for (const ySide of y) {
flags[`--bevel-${ySide}${xSide}`] = '1';
}
corners[`.bevel-${xSide}`] = flags;
}
// Single corner utilities, e.g. .bevel-tl, and .bevel-all
let all = {};
for (const ySide of y) {
for (const xSide of x) {
const flag = {
[`--bevel-${ySide}${xSide}`]: '1',
};
corners[`.bevel-${ySide}${xSide}`] = flag;
all = { ...all, ...flag };
}
}
corners['.bevel-all'] = all;
const varBevel = `var(--bevel, ${base}rem)`;
const utilities = {
'.bevel': {
'--tl': `calc(var(--bevel-tl, 0) * ${varBevel})`,
'--tr': `calc(var(--bevel-tr, 0) * ${varBevel})`,
'--bl': `calc(var(--bevel-bl, 0) * ${varBevel})`,
'--br': `calc(var(--bevel-br, 0) * ${varBevel})`,
'clip-path': `polygon(
0 var(--tl, 0),
var(--tl, 0) 0,
calc(100% - var(--tr, 0)) 0,
100% var(--tr, 0),
100% calc(100% - var(--br, 0)),
calc(100% - var(--br, 0)) 100%,
var(--bl, 0) 100%,
0 calc(100% - var(--bl, 0))
)`,
},
...absoluteSizes,
...relativeSizes,
...corners,
};
addUtilities(utilities, {
variants: ['responsive', 'hover'],
});
});
module.exports = BevelPlugin;
<img
class="bevel bevel-tl bevel-br bevel-xl"
src="https://via.placeholder.com/150"
alt="Example image with bevelled corners"
/>
module.exports = {
plugins: [
require('./bevel-plugin'),
// Other plugins...
],
// Other config options...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment