Skip to main content
Inspiring
November 29, 2018
Answered

Is it possible to use variables in CSS?

  • November 29, 2018
  • 3 replies
  • 1206 views

I know you can define multiple classes at once, by separating them with commas... but can you do the opposite?

Something like...

$stringA = 500px

.class1 { min-width: $stringA;px }

.class2 { max-width: $stringA;px }

This isn't anything I'm trying to do specifically, let's not focus too much on the example; I'm just trying to find out if there's a way to define a variable in one location and call it in multiple other locations (with or without the help of php).

Thanks!

This topic has been closed for replies.
Correct answer ALsp

See this page at Mozilla Developer:

Using CSS custom properties (variables) - CSS: Cascading Style Sheets | MDN

3 replies

Jon Fritz
Community Expert
Community Expert
November 29, 2018

CSS Variables are awesome, when they work, and a lot of unnecessarily duplicated code, when they don't.

Since everything needs to be written out normally, as the fallback for most Microsoft browsers, css variables aren't quite worth using yet in my opinion. However, they are definitely worth knowing for the time when IE usage drops to near zero for your regularly updated sites.

CSS Variables

ALsp
Legend
November 29, 2018

It truly is amazing how these threads seem to have a life of their own

I can cite ways in which they can be used now, in limited roles, even as a self-healing fallback for other things IE doesn't support. In fact, almost like an @supports rule. But I think the original poster might be overwhelmed,

pziecina
Legend
November 29, 2018

ALsp  wrote

It truly is amazing how these threads seem to have a life of their own

And just to prove it -

No version of Dw supports the use of css variables, (doesn't even support srcset/picture, and those were a w3c recommendation status over 2 years ago).

So use, but expect Dw to flag as error.

anissa_thompson
Community Expert
Community Expert
November 29, 2018

ALsp​ provided a simple solution. For reinforcement, take a look at this simple demo video:

CSS Variables without Sass? Learn how to use CSS Variables (Tutorial) - YouTube

Hope this helps! Make sure to press "✔ Correct Answer" on this post if this answers your question. Happy Creating!Anissa • @anissat
ALsp
ALspCorrect answer
Legend
November 29, 2018