Is it possible to define constants in CSS?

Not with plain CSS, but there are some CSS extensions that you could use, like Sass or less-css.

Here's an example of Less CSS:

@color: #4D926F;

#header {
  color: @color;
}
h2 {
  color: @color;
}

Yes, using classes is a good approach, but it is now possible to declare variables in CSS. And variables (especially color ones) are incredibly useful when you declare the same color (one where you need the hex value, if you use an integrated color it doesn't really matter as much).

And this is using plain CSS (and tbh, not nearly as elegant as using SASS or lessCSS) but it works for purposes of plain CSS. First off, define the actual variable in the :root block. You can define it in e.g. a p block as well (or anything else for that matter) but it'll only be available in that block. So to make sure it's globally accessible, put it in the root block:

:root {
  --custom-color: #f0f0f0;
}

And using the var method (without the var method it won't be resolved as an actual reference) you can then reference it later:

p{
    color: var(--custom-color);
}

Since the :root block is (like all other CSS declarations) a fully functioning block that references elements, you can't declare something like:

:root{
    color: #00ff00;
}

That would reference the color attribute of every single element and set it to (in this example) #00ff00. Every variable name you declare has to start with --, meaning you can do:

:root{
    --color: #00ff00;
}

And again, if you can, use something like SASS or lessCSS. The ability to declare them by writing @color = #fff* and referencing with @color* is much easier than dealing with plain CSS and having to use the var keyword every time you want to access a custom property.

And you can access inline CSS with JS to get and/or alter the properties:

//Inline CSS
element.style.getPropertyValue("--custom-color");

// get variable from wherever
getComputedStyle(element).getPropertyValue("--custom-color");

// set variable on inline style
element.style.setProperty("--custom-color", "#f0f0f0");

NOTE!

This is a recently added feature, so browser compatibility is important to check. Especially firefox is worth paying extra attention to, as it has a gap between the introduction of the variable declarations themselves and the var() method. caniuse currently estimates 91.65% of users run a browser with support for the method.

* with lessCSS it's @color, with SASS it is $color


In CSS, you can declare your constant in :root block:

:root {
  --main-bg-color: #1596A7;
}

And using with the var() method:

.panel-header {
    background: var(--main-bg-color);
    color: ...
}

Tags:

Css