I use a few colors throughout my CSS stylesheet. For example
#testdiv{
background: #123456;
}
Is it possible to define that color by name so I can reference it in the css sheet like this
#testdiv{
background: COLORNAME;
}
|
I use a few colors throughout my CSS stylesheet. For example
Is it possible to define that color by name so I can reference it in the css sheet like this
|
|||||
|
|
It is probably a better practice to define a CSS class and re-use it on each element you want to assign the color to rather than coding it to a specific element. Like so:
It also helps to know that an element can have multiple classes applied so you can break out your "Constant" element values into separate classes and apply more than one as needed.
|
|||||||||||||||||||||
|
|
Not with plain CSS, but there are some CSS extensions that you could use, like SASS or less-css. Here's an example of less css:
|
|||||||||
|
|
There are a couple of proposals for this, so it might happen soon, but nothing has yet been standardised as far as I know. The problem with using CSS classes for this is that they are no help if you want to use the same value for different properties, for example if you want to use a particular color value for a border on one element, and a background-color on another. |
|||||
|
|
You can have constants in a
Then you can use them in the CSS file like this:
After that you can use them programmatically like this:
|
|||||
|
|
Nowadays, using preprocessors like the above is a common practice for a better front-end development workflow. It helps you being more organized and features like variables or mixins are some of the reasons they worth taking into consideration. |
|||||
|
|
The standard way to do this is PHP. Add #define statements at the beginning of your CSS file, like
Instead of linking to the CSS file in the head of your HTML file, run a PHP script at that location. The script loads the CSS file, replaces all occurrences of Alternatively, you could upload the source file (also using PHP), use PHP to create a CSS file once where all occurrences of #defines are replaced, and use that file in your HTML. This is more efficient, since you're doing the conversion only once, at the upload, instead of every time you load the HTML file. |
||||
|
|