MDN self-hosted library · e01.org

Registering custom properties in CSS

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

css
:root {
  --myColor: #bada55;
}
main {
  --myColor: #cacaca;
}
main:hover {
  --myColor: #aabbbbaa;
}
@media (width < 750px) {
  main {
    --myColor: #aabbbbaa;
  }
}

.circles {
  --myColor: 45deg;
}
css
@property --myColor {
  syntax: "<color>";
  inherits: true;
  initial-value: #bada55;
}

main:hover {
  color: var(--myColor);
  animation: color-change 2s linear forwards;
}

@keyframes color-change {
  to {
    color: red;
  }
}

.circles {
  --myColor: 45deg;
}
css
@property --rotation {
  syntax: "<angle>";
  inherits: false;
  initial-value: 45deg;
}
html
<div class="container">
  <div class="item one">Item one</div>
  <div class="item two">Item two</div>
  <div class="item three">Item three</div>
</div>
css
@property --item-size {
  syntax: "<percentage>";
  inherits: true;
  initial-value: 40%;
}
js
window.CSS.registerProperty({
  name: "--item-color",
  syntax: "<color>",
  inherits: false,
  initialValue: "aqua",
});
css
.container {
  --item-size: 20%;
  --item-color: orange;
}
.two {
  --item-size: initial;
  --item-color: inherit;
}
.three {
  --item-size: 1000px;
  --item-color: xyz;
}
css
.item {
  width: var(--item-size);
  height: var(--item-size);
  background-color: var(--item-color);
}