Using variables for a hex color

355
July 29, 2017, at 11:09 AM

Using HTML/CSS/JavaScript, Is there a way to use variable to control a hex color value, so I could say something like: color #variable1, variable2, variable3, a b c, and for example variable 1 2 and 3 are 1, 2 and 3, so the color code would be #123abc.

I guess what I'm asking is if you can use variables in place of an identifier for color if that makes sense. Thanks!

Answer 1

You can't really use variables in CSS for colors. You could use something like Sass or Less which are pre-processors to do what you want tho.

EDIT as discussed in other answers you can use variables in CSS. This feature is very new and only works on super modern new browsers. So there are still benefits to using the above pre-processors since it is more compatible with browsers as it just gets converted into standard CSS.

Answer 2

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

The HTML

  <h1 id="foo">Hello</hi>

The output would result in "Hello" being #06c, as defined above.

See Custom Properties for Cascading Variables

Answer 3

No, what you are describing is not possible in CSS. But it is possible to store the color in a javascript variable and change the value dynamically.

EDIT As other people have pointed out, variables are now supported in the latest releases of certain browsers. That being said, I would recommend using Less or Sass in case you need to support any old browser.

var color1 = "#123abc";
var myElement = document.querySelector("#myDiv");
myDiv.style.backgroundColor = color1;
Rent Charter Buses Company
READ ALSO
How to create a dynamicly hhanging php index Number?

How to create a dynamicly hhanging php index Number?

I created a DataTable, which I use with server side, and everything works wellNow I have a column with the name "price" and another column with "rank"

261
how to import Helper class in react

how to import Helper class in react

I am creating a helper class in reactThe image below shows my setup:

510
if (x) &hellip; gives Reference Error: x is not defined

if (x) … gives Reference Error: x is not defined

I thought the following would work, whether x is declared or assigned a value or not:

479
Best way to have absolute imports with Webpack 2?

Best way to have absolute imports with Webpack 2?

I'm in the process of setting up a Webpack configuration for a React project and I want to be able to import my components like this:

291