Sub topic 8
Working with Custom Properties from JavaScript
This chapter assumes you can write custom properties and read them with var(), and that you know how they inherit. It also assumes you can select elements with the DOM API (document.querySelector, event listeners). Everything here builds on the fact that custom properties are ordinary CSS declarations. JavaScript can set them as inline styles and read their computed values.
The two directions
JavaScript touches custom properties in two ways:
- Writing:
element.style.setProperty(name, value)adds an inline declaration to one element. CSS rules that usevar()update automatically. - Reading:
getComputedStyle(element).getPropertyValue(name)returns the value the cascade produced for that element.
JavaScript does not need to know which rules use the property. It changes one value, and the browser recalculates styles. This is the main advantage over setting many individual properties from a script.
const root = document.documentElement;
root.style.setProperty('--brand-color', '#e91e63');
const value = getComputedStyle(root)
.getPropertyValue('--brand-color')
.trim();
console.log(value);Writing with setProperty
setProperty takes the property name, the value, and an optional priority:
const box = document.querySelector('.box');
box.style.setProperty('--gap', '12px');
box.style.setProperty('--gap', '16px', 'important');
box.style.removeProperty('--gap');Four rules matter in practice.
- Include the two dashes. The name is
'--gap', not'gap'. - Dot and bracket notation do not work.
box.style.gapis the realgapproperty.box.style['--gap'] = '12px'does not reliably set a custom property. Always usesetProperty. - Values are strings. If you pass a number, JavaScript converts it to a string.
setProperty('--count', 5)stores5, which has no unit. Add units yourself, as in `${n}px`. - The target element sets the scope. The inline declaration applies to that element and, through inheritance, to its descendants. Setting on
document.documentElementaffects the whole page. Setting on a single card affects only that card and its children.
Because the declaration is inline, it beats normal stylesheet rules on the same element. Only a stylesheet declaration marked !important beats it, unless you pass 'important' as the third argument. removeProperty deletes the inline declaration, and the stylesheet value applies again. That makes it a clean way to reset an override.
Example: a persistent accent color
This example connects a color input to a custom property and saves the choice in localStorage.
<label>
Accent
<input type="color" id="accent-picker" value="#0b5fff">
</label>
<button class="cta">Subscribe</button>:root {
--accent: #0b5fff;
}
.cta {
background: var(--accent);
color: white;
border: 0;
padding: 0.5rem 1rem;
}const root = document.documentElement;
const STORAGE_KEY = 'accent-color';
function applyAccent(color) {
root.style.setProperty('--accent', color);
localStorage.setItem(STORAGE_KEY, color);
}
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
applyAccent(saved);
document.querySelector('#accent-picker').value = saved;
}
document.querySelector('#accent-picker').addEventListener('input', (event) => {
applyAccent(event.target.value);
});No CSS rule changes when the user picks a color. The stylesheet defines the default in :root. The inline value on the same element overrides it.
Example: passing pointer position to CSS
Custom properties let JavaScript feed live data into declarative styles. Here the script reports only coordinates, and CSS decides how to draw them.
.spotlight {
background: radial-gradient(
circle at var(--x, 50%) var(--y, 50%),
#ffffff,
#8a8a8a
);
min-height: 12rem;
}const card = document.querySelector('.spotlight');
card.addEventListener('pointermove', (event) => {
const rect = card.getBoundingClientRect();
card.style.setProperty('--x', `${event.clientX - rect.left}px`);
card.style.setProperty('--y', `${event.clientY - rect.top}px`);
});The fallbacks in var(--x, 50%) keep the card usable before the first pointer event. This is the fallback pattern from the earlier chapter, now doing real work.
Set values on the smallest element that needs them. If you write --x on :root for every mouse move, the browser must check every element that inherits it, and a large page can slow down. Writing to the element that uses the value limits that work.
Reading with getComputedStyle
getComputedStyle(element) returns a live object describing the final styles of an element. Call getPropertyValue on it with the custom property name:
const styles = getComputedStyle(document.querySelector('.card'));
const space = styles.getPropertyValue('--space');The result reflects the cascade and inheritance, so you get the value that applies to that element. If a parent sets --space: 8px and a child sets nothing, reading it from the child gives 8px. If .card overrides it to 16px, reading from .card gives 16px, and reading from its parent still gives 8px.
Reading from style versus computed style
| Call | What it returns | Typical use |
|---|---|---|
| `el.style.getPropertyValue('--x')` | Only the inline declaration on that element. Empty string if none. | Checking whether your script already set an override. |
| `getComputedStyle(el).getPropertyValue('--x')` | The cascaded, inherited value from any source. | Reading the value actually in effect. |
| `el.style.setProperty('--x', v)` | Nothing. Adds or replaces the inline declaration. | Writing. |
| `el.style.removeProperty('--x')` | The old inline value. Deletes the inline declaration. | Resetting to the stylesheet value. |
A frequent bug is reading el.style.getPropertyValue and expecting to see a value that comes from a stylesheet. It returns an empty string, because nothing is inline.
What the returned string looks like
For an unregistered custom property, the computed value is essentially the text you wrote, with any var() references inside it already substituted. Several consequences follow:
- The value is a string.
--count: 3gives"3", not the number3. - Units are not converted.
--space: 0.5remreturns"0.5rem", not a pixel size. calc()is not evaluated.--double: calc(var(--space) * 2)returns the textcalc(8px * 2).- A property that is not defined returns an empty string, not
nullorundefined. - Whitespace may surround the value. Call
.trim()before comparing it.
Wrap these facts in small helpers so the rest of your code does not repeat them:
function readToken(element, name, fallback = '') {
const value = getComputedStyle(element).getPropertyValue(name).trim();
return value === '' ? fallback : value;
}
function readNumber(element, name, fallback = 0) {
const parsed = parseFloat(readToken(element, name));
return Number.isNaN(parsed) ? fallback : parsed;
}
console.log(readToken(document.body, '--brand-color', 'not set'));
console.log(readNumber(document.body, '--columns', 3));readNumber ignores the unit. That is fine for --columns: 4 but wrong for --space: 0.5rem, because you get 0.5 and not a pixel count.
Resolving a length to pixels
When you need a real pixel number, let the browser compute it. Apply the custom property to a real CSS property on a temporary element, then read the computed result:
function resolveLength(element, name) {
const probe = document.createElement('div');
probe.style.position = 'absolute';
probe.style.visibility = 'hidden';
probe.style.width = `var(${name})`;
element.appendChild(probe);
const pixels = parseFloat(getComputedStyle(probe).width);
probe.remove();
return pixels;
}
console.log(resolveLength(document.body, '--space'));The probe inherits the custom property from element, width accepts any length, and getComputedStyle converts rem, em, or calc() into pixels. This works only for values that are valid lengths. A percentage would resolve against the probe's containing block, not give you a fixed pixel count.
A registered property (covered in a later chapter) avoids this workaround. When you register a property with a syntax such as <length>, the browser computes it to an absolute value, so getPropertyValue returns a canonical result.
Timing and cost
The browser must apply style changes before getComputedStyle can give an accurate answer. Calling getPropertyValue right after setProperty forces a style recalculation. One read is cheap. Alternating many writes and reads in a loop can slow a page. Batch your work: do all the reads first, then all the writes.
Also read the value after the stylesheet has loaded. A script in the document head that reads --brand-color before the stylesheet applies gets an empty string. Run such code on DOMContentLoaded, or after the load event if the stylesheet is external and your script needs its final values.
Invalid values from JavaScript
setProperty accepts almost any text for an unregistered custom property, because the browser cannot check the value without knowing where it will be used. This means a typo does not throw an error:
const el = document.querySelector('.box');
el.style.setProperty('--size', 'twelve pixels');
console.log(el.style.getPropertyValue('--size'));The script prints twelve pixels, so the write looks successful. The problem only shows up when a rule such as width: var(--size) tries to use the value. At that point the declaration becomes invalid at computed-value time, and the property falls back to its inherited or initial value. Nothing is reported in the console.
To catch such mistakes, validate the value in your script before writing it, or register the property with a syntax so the browser rejects wrong values. Debugging steps:
- Read the custom property from the element with
getComputedStyle. If it is wrong, the problem is in your script or the cascade. - If it is right, check the property that uses it in the browser's style inspector. A crossed-out declaration with an "invalid at computed-value time" note means the value does not fit that property.
Choosing between JavaScript and CSS
Use JavaScript to write a custom property when the value depends on something CSS cannot see: pointer position, scroll offset, user input, data from a server, or a stored preference. Keep presentation rules in CSS. The script should supply a number or a color, and the stylesheet should decide how to use it.
For states that CSS can detect itself, such as prefers-color-scheme or :hover, do not use a script. Redefine the custom property in CSS, as in the theming chapter. Script-driven changes also need JavaScript to be running, and a stylesheet-only solution works without it.
Summary of the working model
- Write with
style.setPropertyand remove withstyle.removeProperty. - Read the effective value with
getComputedStyle(el).getPropertyValue. - Values are strings. Trim them and parse them yourself.
- Set values on the narrowest element that needs them.
- Unregistered properties are not validated or converted. Registration changes that.
Exercise
A stylesheet defines :root { --size: 2rem; } and .panel { --size: 3rem; }. A script runs document.querySelector('.panel').style.setProperty('--size', '40px'). What do getComputedStyle(panel).getPropertyValue('--size') and panel.style.getPropertyValue('--size') return? What does each return after panel.style.removeProperty('--size')?
Show answer
Before removal, both return 40px, because the inline value wins over the .panel rule and is also the only inline declaration. After removal, the computed call returns 3rem (the .panel rule applies again), and the inline call returns an empty string because nothing is set inline.
Exercise
Write a function setHue(value) that stores a number from 0 to 360 in a custom property --hue on the root element, and explain why document.documentElement.style['--hue'] = 200 is the wrong way to do it. Then write the CSS that uses --hue for a background color with a fallback of 210.
Show answer
function setHue(value) { document.documentElement.style.setProperty('--hue', String(value)); }. Bracket assignment is wrong because custom properties are not exposed as named properties on the style object, so it does not reliably set the declaration. setProperty is the supported API. CSS: .banner { background: hsl(var(--hue, 210) 70% 50%); }.