Today I Learned - Rocky Kev

TIL targetting CSS variables with Javascript

POSTED ON:

TAGS:

You can target CSS variables with JS, to change design elements without hacking the element itself.

This is super cool because now, you can actually focus on targetting CSS variables, rather than each individual JS element, and have it ripple effect to all your other CSS elements.

:root {
--pagebackground: rebeccapurple;
}

body {
background: var(--pagebackground);
}
let bg = getComputedStyle(document.documentElement).getPropertyValue('--pagebackground');

document.documentElement.style.setProperty('--pagebackground', 'yellow');

See the Pen Targetting CSS Variables with JS by rockykev (@rockykev) on CodePen.

REFERENCE:
https://christianheilmann.com/2021/02/08/sharing-data-between-css-and-javascript-using-custom-properties/


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)')