Joel Banks
Joel Banks

Reputation: 149

Using variables for a hex color

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!

Upvotes: 2

Views: 9876

Answers (4)

jack
jack

Reputation: 1391

Another unmentioned option, if you use, say, PHP, is to use PHP variables like this:

<?php $color = '333444'; ?>
<style type="text/css">
    .class {
        color: #<?php $color; ?>;
    }
</style>

This is best used when you generate the entire style (for whatever purpose) from your php server code.

$color = '333444';

echo "
    <style>
        .class {
            color: #$color;
        }
    </style>
";

Beyond the above, just know that you can do this, but this is not the best solution. Let's wait until CSS4 or 5, they might add variables there.

Upvotes: 1

Wai Yan
Wai Yan

Reputation: 582

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;

Upvotes: 2

Charlie Fish
Charlie Fish

Reputation: 20576

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.

Upvotes: 1

LLL
LLL

Reputation: 115

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

Upvotes: 4

Related Questions