Today I Learned - Rocky Kev

TIL about this method to generate infinite Utility Helpers with CSS

POSTED ON:

TAGS:

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:

TIL the alternate keyword

If 'alternate' appears along with the stylesheet keyword, the linked file is an alternative stylesheet. It won’t be applied to the document, but it will be ready for when we need it.

TIL Logical Properties

For that sweet sweet Internationalization you want to avoid directional words like 'left', 'right', 'top', and 'bottom'.

TIL Using pseudo-classes in your querySelector!

let notTuna = document.querySelectorAll('.sandwich:not(.tuna)')