{"id":246274,"date":"2016-10-25T05:30:29","date_gmt":"2016-10-25T12:30:29","guid":{"rendered":"http:\/\/css-tricks.com\/?p=246274"},"modified":"2016-10-25T06:46:02","modified_gmt":"2016-10-25T13:46:02","slug":"difference-between-types-of-css-variables","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/difference-between-types-of-css-variables\/","title":{"rendered":"What is the difference between CSS variables and preprocessor variables?"},"content":{"rendered":"

Variables are one of the major reasons CSS preprocessors exist at all. The ability to set a variable for something like a color, use that variable throughout the CSS you write, and know that it will be consistent, DRY, and easy to change is useful. You can use native CSS variables (“CSS Custom Properties”) for the same reasons. But there are also some important differences that should be made clear.<\/p>\n

<\/p>\n

A simple example of preprocessor variable usage is like this:<\/h3>\n
$brandColor: #F06D06;\r\n\r\n.main-header {\r\n  color: $brandColor;\r\n}\r\n.main-footer {\r\n  background-color: $brandColor;\r\n}<\/code><\/pre>\n

That was the SCSS variant of Sass<\/a>, but all CSS preprocessors offer the concept of variables: Stylus<\/a>, Less<\/a>, PostCSS<\/a>, etc.<\/p>\n

The above code would do nothing in a browser. The browser wouldn’t understand the declarations and toss them out. Preprocessors need to compile into CSS to be used. This code would compile to:<\/p>\n

.main-header {\r\n  color: #F06D06;\r\n}\r\n.main-footer {\r\n  background-color: #F06D06;\r\n}<\/code><\/pre>\n

This is now valid CSS. The variable was part of the preprocessor language, not CSS itself. Once the code compiles, the variables are gone.<\/p>\n

More recently, native CSS has started supporting CSS variables, or “CSS Custom Properties”. It allows you to work with variables directly in CSS. There is no compiling.<\/p>\n

A simple example of CSS custom property usage is like this:<\/h3>\n
:root {\r\n  --main-color: #F06D06;\r\n}\r\n\r\n.main-header {\r\n  color: var(--main-color);\r\n}\r\n.main-footer {\r\n  background-color: var(--main-color);\r\n}<\/code><\/pre>\n

These two demos achieve the exact same thing. We were able to define a color once and use it twice. <\/p>\n

So then… why use one over another? <\/p>\n

Why would you use native CSS custom properties?<\/h3>\n