skip to content

CSS Variables


I've been using a scss for a while. With that, comes variables which are easily defined like so: $color-variable: #f06d06. If this is more or less the reason, why you're a using scss instead of regular css. You might not need to.

You can use CSS's custom properties like so:

/*
 Declare the variables on the root element
 to make them available globally
*/
:root {
 --color-1: red;
 --color-2: blue;
}

html,
body {
 background-color: var(--color-1);
 color: var(--color-2);
}

/*
    You can later overwrite variables 
    and scope to them to specific elements
*/
main {
 --color-1: yellow;
 background: var(--color-1);
}

Pretty nifty if you ask me!

Manipulating the properties with JS

Manipulating CSS's custom properties is super easy! You can both get the values and set them like so:

See the Pen CSS Custom Properties by Tristan White (@triss90) on CodePen.