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.

JavascriptData Fetching

Code

javascriptsnippet
20 lines
// 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: document are 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

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.