Using Css Custom Properties Variables Not Working

style sheet have very large amounts of CSS, often with a lot of repeated values. i read somewhere about variable in CSS . below my code is . but it is not working

element {
      --main-bg-color: brown;
    }

and i am using the variable here but it is not working

body {
  background-color: var --main-bg-color;
}
2

5 Answers

You did everything right, just keep the variables in (put variable here)

element {
  --main-bg-color: brown;
}
body {
  background-color: var(--main-bg-color);
}
2

var() notation works like a method

var(<custom-property-name>)

might consider putting your variables in a :root selector...

:root {
  --main-bg-color: brown;
}
/* The rest of the CSS file */
body {
  background-color: var(--main-bg-color);
}

:root is similar to global scope, but the element itself (ie body { --myvar: ... }) or ancestor elements (ie html { --myvar: ... }) can also be used to define variables

Refer to MDN reference page. A brief, to use custom variables you need to place them inside :root selector:

:root {
  --main-bg-color: brown
}

In order to use it in another selector yo use var():

body {
  background-color: var(--main-bg-color)
}
1

For me, the problem was that @charset "UTF-8"; was not the very first characters in the css file, and this messed up the :root{--my-variable: large }.

You need to add var(--my-variable) when using the variables.

But that's not something you should use CSS custom properties (variables) for.

Bear in mind some browser can't understand CSS variables, most noticeably IE. So using any pre-processor instead will be better for compatibility, as they are compiled to regular CSS values. Either SASS, LESS, POSTCSS... whatever floats your boat.

CSS custom properties are much more powerful than pre-processor ones, as they can be changed at runtime with javascript and be used in all sorts of awesome ways, but when you're using them as regular variables, pre-processor variables are always better for compatibility.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest