user3550879
user3550879

Reputation: 3469

Using variables in CSS

Is there/what is the best way to set a variable in my CSS stylesheet that is cross browser compatible?

I want to set

color: #123456;

into a variable since I am using it in numerous different spots and if I choose to change that colour I want it all the change.

Upvotes: 1

Views: 877

Answers (3)

HarrisJT
HarrisJT

Reputation: 319

Its not well supported, but this is how it works according to http://www.w3.org/TR/css-variables/

Custom properties define variables, referenced with the var() notation, which can be used for many purposes. For example, a page that consistently uses a small set of colors in its design can store the colors in custom properties and use them with variables:

:root {
  --main-color: #06c;
  --accent-color: #006;
}

/* The rest of the CSS file */

#foo h1 {
  color: var(--main-color);
}

You can to use a preprocessor like SASS, which has this done much better.

Upvotes: 1

DA.
DA.

Reputation: 40691

CSS Variables are a thing but the only browser that has any support for it at this time is Mozilla.

Alternative options:

  • use Javascript and/or a server-side language to set the variables in your CSS file programatically.
  • use a CSS preprocessor like SASS. This allows you to create variables. You do have to re-deploy your CSS each time.
  • consider handling colors a different way in your markup.

Regarding the last one, instead of hardcoding a color into an elements style:

<div class="thisElement"></div>

.thisElement {
    font-size: 13px
    background: red;
    color: #123456;
}

consider using classes for this instea:

<div class="thisElement color1"></div>

.thisElement {
    font-size: 13px
    background: red;
}

.color1 {
    color: #123456;
}

That way you only need to declare the color once in your style sheet. This is essentially 'object oriented CSS'. The idea is that instead of applying monolithic style declarations for each DOM object, you instead declare 'snippets' of style to a bunch of separate classes, then assign those separate classes as you see fit to each DOM object.

In a sense, you've turned the class name, itself, into the variable. You declare it in your CSS once, then use it as many times as needed in your HTML.

Upvotes: 4

DasSaffe
DasSaffe

Reputation: 2198

If you want to do it in native css you can't. However, you can use technologies / preprocessors like SASS / LESS to achieve exactly what you are describing.

Cross-browser compatibility, variables and calculating.

Once you get used to the syntax (which is really easy to understand and modify) and you are ready to go, SASS creates the "plain" css files for you. Keeps your code clean, simple and easy to maintain.

Have a look at this: http://sass-lang.com/

Also, here you can find some examples and snippets to have a first impression.

Upvotes: 1

Related Questions