ravins
ravins

Reputation: 81

How to use CSS custom variables for properties

My stylesheets have large amounts of styles declared, often with a lot of repeated values. I read about variables in CSS to solve that problem.

I tried to use them, but it is not working:

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

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

What am I doing wrong?

Upvotes: 7

Views: 51526

Answers (6)

sethugs63
sethugs63

Reputation: 1

If you want to declare them globally, I would recommend to use it in: * { --var : #colorName; }. This has actually helped me in Angular application.

Upvotes: 0

Facundo Corradini
Facundo Corradini

Reputation: 3913

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.

Upvotes: 0

Dallas Clarke
Dallas Clarke

Reputation: 269

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 }.

Upvotes: -1

Hasanuzzaman Sattar
Hasanuzzaman Sattar

Reputation: 600

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

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

Upvotes: 16

David Daza
David Daza

Reputation: 155

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)
}

Upvotes: 0

MikeM
MikeM

Reputation: 27405

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

Upvotes: 7

Related Questions