TIL about this method to generate infinite Utility Helpers with CSS
POSTED ON:
TAGS: css
In Tailwind CSS, you can use things like:
<div class="p-8">I add padding - rem2 to this element!</div>
<div class="p-24">I add padding - rem6 to this element!</div>
<div class="p-32">I add padding - rem8 to this element!</div>
That can be done using something like:
$space-stops: (
'0': 0,
'1': 0.25rem,
'2': 0.5rem,
'3': 0.75rem,
'4': 1rem,
'5': 1.25rem,
'6': 1.5rem,
'7': 1.75rem,
'8': 2rem,
'9': 2.25rem,
'10': 2.5rem,
// ...
);
@each $key, $val in $space-stops {
.p-#{$key} {
padding: #{$val} !important;
}
}
But apparently, thanks to CSS variables, you can also do this:
:root {
--p: 0;
}
[style*='--p:'] {
padding: calc(0.25rem * var(--p)) !important;
}
<div style="--p:8">I add padding - rem2 to this element!</div>
<div style="--p:24">I add padding - rem6 to this element!</div>
<div style="--p:32">I add padding - rem8 to this element!</div>
Via: Efficient Infinite Utility Helpers Using Inline CSS Custom Properties and calc()
Related TILs
Tagged: css