setProperty Writes CSS Custom Properties
setProperty writes CSS custom properties with optional important priority, and getComputedStyle reads back the parsed value for state-driven theming.
Code
// CSS 自定义属性用 style.setProperty 写入;getComputedStyle 读回的是解析后的值
const card = document.createElement('section');
card.style.cssText = 'background: var(--card-accent); padding: 16px;';
document.body.append(card);
// setProperty(属性名, 值):普通优先级
card.style.setProperty('--card-accent', 'rebeccapurple');
console.log(getComputedStyle(card).getPropertyValue('--card-accent'));
// 第三个参数写 important:带上优先级
card.style.setProperty('--card-accent', 'seagreen', 'important');
console.log(getComputedStyle(card).getPropertyValue('--card-accent'));
// 值传空字符串即移除该属性
card.style.setProperty('--card-accent', '');
console.log(JSON.stringify(getComputedStyle(card).getPropertyValue('--card-accent')));
// 状态驱动:只改一个变量,引用它的派生样式跟着变
card.style.setProperty('--badge-offset', '6px');
console.log(getComputedStyle(card).getPropertyValue('--badge-offset'));setProperty Writes CSS Custom Properties: inside the code
State lives in top-level bindings: card.
Watch out for
- No package installation, no environment variables, no setup steps.
- A browser is the runtime here:
documentare not available in Node.
Key statements
card.style.cssText = 'background: var(--card-accent); padding: 16px;';
card.style.setProperty('--card-accent', 'seagreen', 'important');
card.style.setProperty('--card-accent', 'rebeccapurple');
Interactive Tools for This Topic
Aspect Ratio CalculatorSimplify a width-to-height ratio, show its decimal value, and derive a matching height for a new width.Border Radius PreviewPreview four-corner border-radius values on a live box and copy the generated shorthand border-radius CSS declaration.Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.
FAQ
- Does setProperty Writes CSS Custom Properties run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.