Sub topic 8
Working with Custom Properties from JavaScript
This chapter assumes you know how to declare custom properties and read them with var(). It also assumes you understand scope and inheritance, and that you can select elements with document.querySelector. Here you will read and write custom properties from scripts, and see where the common mistakes happen.
Why use JavaScript with custom properties
A custom property is a value that CSS rules read through var(). If a script changes that value, every rule that reads it updates on the next render. The script does not need to know which rules depend on the value. This keeps the split clean: CSS decides how a value is used, and JavaScript decides what the value is.
Typical uses are a user-chosen accent color, a pointer position, a scroll progress value, or a measured element size.
Writing a custom property
Use style.setProperty() on an element. The first argument is the full name, including the two dashes. The second is the value as a string.
const root = document.documentElement;
root.style.setProperty('--brand-color', '#e91e63');This writes an inline style on the <html> element. Because custom properties inherit, every descendant that reads --brand-color sees the new value, unless a closer element redefines it.
Inline styles have high priority in the cascade. A value set this way beats a stylesheet rule on the same element, which is usually what you want for a user's choice.
To remove the inline value and let the stylesheet apply again, use removeProperty():
document.documentElement.style.removeProperty('--brand-color');Dot notation does not work
Standard properties can be set as el.style.color = 'red'. Custom properties cannot be set this way, because el.style['--brand-color'] is not a defined property of the style object. Always use setProperty.
Reading a custom property
There are two places to read from, and they give different answers.
el.style.getPropertyValue('--x')returns only what was set inline on that element. It returns an empty string if the value came from a stylesheet or from an ancestor.getComputedStyle(el).getPropertyValue('--x')returns the value that applies to the element after the cascade and inheritance.
Most of the time you want the computed value.
const root = document.documentElement;
const value = getComputedStyle(root)
.getPropertyValue('--brand-color')
.trim();
console.log(value);Call .trim() on the result. For an unregistered custom property, the browser can keep the whitespace that appeared in the declaration, so --brand-color: #0b5fff; may come back as " #0b5fff". An undefined property returns an empty string, so you can test for that.
const card = document.querySelector('.card');
const accent = getComputedStyle(card).getPropertyValue('--card-accent').trim();
if (accent === '') {
console.log('--card-accent is not defined for this element');
}The value is text, not a number
For an unregistered property, the browser returns the declared text. Given --space: 8px;, you get the string "8px". If you declared --count: 3, you get "3", and you must convert it yourself.
const space = parseFloat(
getComputedStyle(document.documentElement).getPropertyValue('--space')
);
console.log(space * 2); // 16The browser also does not resolve var() or calc() in the string for unregistered properties. If --double: calc(var(--space) * 2), reading --double returns that expression as text, not 16px. To get a resolved number, apply the value to a real property and read that instead, or register the property with a type (covered in a later chapter).
A worked example: a theme switcher
This script keeps a user's color choice in a custom property, and restores it when the page loads.
<input type="color" id="picker" value="#0b5fff">
<button class="button">Save</button>
<style>
:root { --brand-color: #0b5fff; }
.button { background: var(--brand-color); color: white; }
</style>
<script>
const root = document.documentElement;
const picker = document.getElementById('picker');
const saved = localStorage.getItem('brand');
if (saved) {
root.style.setProperty('--brand-color', saved);
picker.value = saved;
}
picker.addEventListener('input', () => {
root.style.setProperty('--brand-color', picker.value);
localStorage.setItem('brand', picker.value);
});
</script>No CSS rule changes when the user picks a color. The single setProperty call updates the button and anything else that reads --brand-color.
Scoping writes to one element
Set the property on a specific element to limit the effect. This follows the scope rules from earlier chapters.
const card = document.querySelector('.card');
card.style.setProperty('--card-color', 'tomato');Only .card and its descendants see the new value. Per-element values are a common way to pass data into CSS, for example an index for staggered animations:
document.querySelectorAll('.item').forEach((item, i) => {
item.style.setProperty('--index', i);
});.item {
transition-delay: calc(var(--index) * 50ms);
}Here setProperty accepts the number i, which the browser converts to a string.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| `el.style.getPropertyValue` for a stylesheet value | Empty string | Use `getComputedStyle` |
| Forgetting `--` in the name | Nothing is set or read | Pass the full name, such as `--space` |
| Not trimming the result | Comparisons fail because of leading spaces | Call `.trim()` |
| Using `el.style.--x = ...` | Syntax error | Use `setProperty` |
| Doing math on the string | `NaN` or string concatenation | Use `parseFloat` |
Exercise
A stylesheet declares --gap: 12px; on :root. A script calls document.documentElement.style.getPropertyValue('--gap') and gets an empty string. Why, and how do you get 12 as a number?
Show answer
style.getPropertyValue reads only inline styles, and --gap came from a stylesheet. Use parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--gap')), which returns 12.
Exercise
Write one line that gives each element with the class .tile a custom property --i equal to its position in the list, starting at 0, assuming tiles is a NodeList from querySelectorAll('.tile').
Show answer
tiles.forEach((tile, i) => tile.style.setProperty('--i', i));