Anyway to declare "red" = #FF0000, and change it later? [duplicate] - html

I’m working on a CSS file that is quite long. I know that the client could ask for changes to the color scheme, and was wondering: is it possible to assign colors to variables, so that I can just change a variable to have the new color applied to all elements that use it?
Please note that I can’t use PHP to dynamically change the CSS file.

CSS supports this natively with CSS Variables.
Example CSS file
:root {
--main-color:#06c;
}
#foo {
color: var(--main-color);
}
For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).
Manipulating a CSS variable in JavaScript/client side
document.body.style.setProperty('--main-color',"#6c0")
Support is in all the modern browsers
Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.

People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.
You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...
At the top of the css file
/********************* Colour reference chart****************
*************************** comment ********* colour ********
box background colour bbg #567890
box border colour bb #abcdef
box text colour bt #123456
*/
Later in the CSS file
.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}
Then to, for example, change the colour scheme for the box text you do a find/replace on
/*bt*/#123456

Yeeeaaahhh.... you can now use var() function in CSS.....
The good news is you can change it using JavaScript access, which will change globally as well...
But how to declare them...
It's quite simple:
For example, you wanna assign a #ff0000 to a var(), just simply assign it in :root, also pay attention to --:
:root {
--red: #ff0000;
}
html, body {
background-color: var(--red);
}
The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS or SASS...
Also, here is a simple JavaScript script, which changes the red value to blue:
const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');

CSS itself doesn't use variables. However, you can use another language like SASS to define your styling using variables, and automatically produce CSS files, which you can then put up on the web. Note that you would have to re-run the generator every time you made a change to your CSS, but that isn't so hard.

You can try CSS3 variables:
body {
--fontColor: red;
color: var(--fontColor);
}

There's no easy CSS only solution. You could do this:
Find all instances of background-color and color in your CSS file and create a class name for each unique color.
.top-header { color: #fff; }
.content-text { color: #f00; }
.bg-leftnav { background-color: #fff; }
.bg-column { background-color: #f00; }
Next go through every single page on your site where color was involved and add the appropriate classes for both color and background color.
Last, remove any references of colors in your CSS other than your newly created color classes.

The 'Less' Ruby Gem for CSS looks awesome.
http://lesscss.org/

Yes, in near future (i write this in june 2012) you can define native css variables, without using less/sass etc ! The Webkit engine just implemented first css variable rules, so cutting edge versions of Chrome and Safari are already to work with them. See the Official Webkit (Chrome/Safari) development log with a onsite css browser demo.
Hopefully we can expect widespread browser support of native css variables in the next few months.

Do not use css3 variables due to support.
I would do the following if you want a pure css solution.
Use color classes with semenatic names.
.bg-primary { background: #880000; }
.bg-secondary { background: #008800; }
.bg-accent { background: #F5F5F5; }
Separate the structure from the skin (OOCSS)
/* Instead of */
h1 {
font-size: 2rem;
line-height: 1.5rem;
color: #8000;
}
/* use this */
h1 {
font-size: 2rem;
line-height: 1.5rem;
}
.bg-primary {
background: #880000;
}
/* This will allow you to reuse colors in your design */
Put these inside a separate css file to change as needed.

Sure can, sort of, thanks to the wonderful world of multiple classes, can do this:
.red {color:red}
.blackBack {background-color: black}
but I often end up combining them anyway like this:
.highlight {color:red, background-color: black}
I know the semantic police will be all over you, but it works.

I'm not clear on why you can't use PHP. You could then simply add and use variables as you wish, save the file as a PHP file and link to that .php file as the style sheet instead of the .css file.
It doesn't have to be PHP, but you get what I mean.
When we want programming stuff, why not use a programming language until CSS (maybe) supports things like variables?
Also, check out Nicole Sullivan's Object-oriented CSS.

You can group selectors:
#selector1, #selector2, #selector3 { color: black; }

You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off

dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.
//create the CSS JSON object with variables and styles
var myCSSObjs = {
cssVariables : {
primaryColor:'#FF0000',
padSmall:'5px',
padLarge:'$expr($padSmall * 2)'
}
'body' : {padding:'$padLarge'},
'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
'.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};
//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();
And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo

EDIT: This answer is no longer current. You should use CSS variables now.
Consider using SCSS. It's full compatible with CSS syntax, so a valid CSS file is also a valid SCSS file. This makes migration easy, just change the suffix. It has numerous enhancements, the most useful being variables and nested selectors.
You need to run it through a pre-processor to convert it to CSS before shipping it to the client.
I've been a hardcore CSS developer for many years now, but since forcing myself to do a project in SCSS, I now won't use anything else.

If you have Ruby on your system you can do this:
http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html
This was made for Rails, but see below for how to modify it to run it stand alone.
You could use this method independently from Rails, by writing a small Ruby wrapper script
which works in conjunction with site_settings.rb and takes your CSS-paths into account, and
which you can call every time you want to re-generate your CSS (e.g. during site startup)
You can run Ruby on pretty much any operating system, so this should be fairly platform independent.
e.g. wrapper: generate_CSS.rb (run this script whenever you need to generate your CSS)
#/usr/bin/ruby # preferably Ruby 1.9.2 or higher
require './site_settings.rb' # assuming your site_settings file is on the same level
CSS_IN_PATH = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files')
CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' )
Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH )
the generate_CSS_files method in site_settings.rb then needs to be modified like this:
module Site
# ... see above link for complete contents
# Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory
# replacing any mention of Color Constants , e.g. #SomeColor# , with the corresponding color code defined in Site::Color
#
# We will only generate CSS files if they are deleted or the input file is newer / modified
#
def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') ,
output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets'))
# assuming all your CSS files live under "./public/stylesheets"
Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in|
filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') ))
# if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file:
if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime)
# in this case, we'll need to create the output CSS file fresh:
puts " processing #{filename_in}\n --> generating #{filename_out}"
out_file = File.open( filename_out, 'w' )
File.open( filename_in , 'r' ).each do |line|
if line =~ /^\s*\/\*/ || line =~ /^\s+$/ # ignore empty lines, and lines starting with a comment
out_file.print(line)
next
end
while line =~ /#(\w+)#/ do # substitute all the constants in each line
line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines
end
out_file.print(line)
end
out_file.close
end # if ..
end
end # def self.generate_CSS_files
end # module Site

Not PHP I'm afraid, but Zope and Plone use something similar to SASS called DTML to achieve this. It's incredibly useful in CMS's.
Upfront Systems has a good example of its use in Plone.

If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.
colors.xml:
<?xml version="1.0"?>
<colors>
<background>#ccc</background>
</colors>
styles.xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
<xsl:template match="/">body {
background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>
Command to render css: xsltproc -o styles.css styles.xsl colors.xml
styles.css:
body {
background-color: #ccc;
}

It’s not possible with CSS alone.
You can do it with JavaScript and LESS using less.js, which will render LESS variables into CSS live, but it’s for development only and adds too much overhead for real-life use.
The closest you can come with CSS is to use an attribute substring selector like this:
[id*="colvar-"] {
color: #f0c69b;
}
and set the ids of all your elements that you want to be adjusted to names starting with colvar-, such as colvar-header. Then when you change the color, all the ID styles are updated. That’s as close as you can get with CSS alone.

Related

Load svg as path

I use webpack via CLI, like webpack --watch.
Goal is to compile JS with SASS and put in some separate html page.
I have some links to svg files in my sass, looking like that:
label {
background: url(../images/checkbox.svg);
}
The problem is that I never get it in the browser after compiling. I have following situations:
If I compile it using svg-loader, in browser I see compiled css is something like that:
background: url([object Object]);
Here is suggested to use svg-url-loader instead.
If I use mentioned svg-url-loader, I have whole page css messed up which makes browser to show raw text instead of styled page.
If I use file-loader, I get css compiled to background:
background: url(37efc0ccedf6fe109636ad1416c29425.svg)
and as I put resulted bundle.js to some other place, I am not happy with copying some files I already have.
If I use raw-loader, I get some xml instead of file name in the url(...), which just doesn't work, showing "wrong property value" error in the css.
I would be happy to get just regular path instead of all that things, like
background: url(../images/checkbox.svg);
So what is correct approach to handle svg in my situation? Thank you.
Ok, I found solution:
{
test: /\.svg$/,
loader: 'file?name=/resources/[path][name].[ext]'
},
{
test: /\.png$/,
loader: 'file?name=/resources/[path][name].[ext]'
}
This way loader preserves name and path and prepends additional /resources/folder.

Efficient way to store and return custom CSS for personalised page visuals

I have a web app that needs to display pages whose CSS values are set via a form. To be clear: not the CSS parameters, just their values are user-defined.
I'm using a framework (jquery mobile). My css file is about 700 lines (the sass file is a little longer but full of comments and variables for colors, margins, etc). There are about a dozen variables inteded to be defined by the user (eg $pageBackgroundColor, $borderWidth, $spanColor), but each variable is used several times in the sass file.
Let's say I now have these dozen variables safely stored in my database, and a user requests a page. How do I provide the necessary CSS?
I could:
compile a minified css file at the time of form submission and link
it when a page is requested (downside: I'm likely to have several thousand CSS files sitting on my server)
compile a minified css text string and dump it between two <style> tags in the <head> (downside: ugliness, no caching, and request handling time increases)
Are there any other options? I looked at one site that does custom visuals for each user and they went for a separate CSS file for each person.
I'm using a Django+Postgres backend, if it's relevant.
You could move the style declarations in which these variables are used to inline CSS, in the <head>. Additionally, you could do this with just a few styles, but it does require you to add more classes to your HTML:
<style type="text/css">
.user-background-color {
background-color: #abc123;
}
.user-color {
color: #abc123;
}
.user-border-color {
border-color: #abc123;
}
</style>
Then your HTML gets additional classes:
<div class="style-1 style-2 user-border-color"></div>
So I went the giant composite heredoc external file route, with the file name saved in the db. It works well enough, but is obviously not fun to edit.

Can XML interact with a CSS style sheet?

Let's say I have a CSS sheet that holds information for how a site that shows system statuses is presented. Depending on the status of the site, one of the following will be an attribute to the status:
#green_status
{
color: white;
text-align: left;
background: url(images/green.jpg) no-repeat;
}
#yellow_status
{
color: white;
text-align: left;
background: url(images/yellow.jpg) no-repeat;
}
#red_status
{
color: white;
text-align: left;
background: url(images/red.jpg) no-repeat;
}
and an XML document that stores details for individual sites and their statuses
<site>
<name>New Site</name>
<headerImage>header image goes here</headerImage>
<systemStatus color="green">Normal</systemStatus>
<networkNotes>System status is normal</networkNotes>
</site>
I am going to use XML DOM to select values from the XML to populate elements of the page. Though after some testing I am still finding that I can change the text of the system's status but not the bar color without actually changing the site's attributes.
I'd like to be able to just change the XML file and set <systemStatus color"red">SYSTEM IS DOWN</systemStatus> and have that change not only the text, but the bar color to "red.jpg" without having to go in to the html and manually edit the status.
So far in order to solve this, I've added the 'color="green, yellow, red"' attribute to my XML elements, added 2 new statuses to the CSS (indicated by the first code block of this question), and have so far been unable to connect the dots.
Is there a way that I can make it to where the changes only need to be made to the XML file to change both the text & bar color for the system status of that site? The end goal here is to be able to just change the XML attribute and text of the systemStatus and change both the bar & the text on the site.
Use the CSS3 attribute selector.
<systemStatus color="green">
CSS:
systemStatus[color='green'] {
background-color:#2f2;
}
You can link a CSS stylesheet to an XML file using this processing instruction:
<?xml-stylesheet href="my-style.css"?>
... rest of document here...
More details about it can be found here: http://www.w3.org/Style/styling-XML
With that, you can add styling to any element and even use attributes in the selector:
systemStatus[color="red"] {
color: red;
}
I think you can also use special selectors like :first-child and such.
Afaik, there is no way to include Javascript in an XML file, but you should be able to tranform the XML into another XML if the current XML doesn't have the structure you need.
In the transformation you can add the elements and properties you need to be able to style it. See also Xml to Xml transformation using XSLT.
What everybody else said, plus you can set the content via CSS too:
systemStatus[color='green']::after {
content: "ALL IS WELL";
}
I suggest using a descriptive term for the attribute rather than explicitly a color, so that you can change your mind later about what the display should be without changing the nomenclature. Something like
<systemStatus status="ok"/>
and in CSS
systemStatus[status="ok"] {
color: green;
background-color: white;
}
XML does not specify any display or formatting, so if you really want to show a text as green, you need to do that using the display language (e.g. HTML or XSL-FO).
You can specify a tag to contain (X)HTML fragment, either as XHTML fragment, e.g.
<site xmlns:h="http://www.w3.org/1999/xhtml">
...
<systemStatus><h:p class="ok" style="color: green;">Normal</h:p></systemStatus>
...
</site>
or as CDATA:
<site>
...
<systemStatus><![CDATA[<p class="ok" style="color: green;">Normal</p>]]></systemStatus>
...
</site>
Your host display language (HTML+Javascript in your case) has to then insert this into the host document's DOM as an (X)HTML fragments or textually with element.innerHTML.
Be careful about inserting with innerHTML from untrusted source though, if the data in the XML file comes untrusted source, they may potentially contain Javascript code, which may then be executed when inserted into the host HTML.

I would like to be able to typedef a color in html, is that possible? [duplicate]

I’m working on a CSS file that is quite long. I know that the client could ask for changes to the color scheme, and was wondering: is it possible to assign colors to variables, so that I can just change a variable to have the new color applied to all elements that use it?
Please note that I can’t use PHP to dynamically change the CSS file.
CSS supports this natively with CSS Variables.
Example CSS file
:root {
--main-color:#06c;
}
#foo {
color: var(--main-color);
}
For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).
Manipulating a CSS variable in JavaScript/client side
document.body.style.setProperty('--main-color',"#6c0")
Support is in all the modern browsers
Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.
People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.
You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...
At the top of the css file
/********************* Colour reference chart****************
*************************** comment ********* colour ********
box background colour bbg #567890
box border colour bb #abcdef
box text colour bt #123456
*/
Later in the CSS file
.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}
Then to, for example, change the colour scheme for the box text you do a find/replace on
/*bt*/#123456
Yeeeaaahhh.... you can now use var() function in CSS.....
The good news is you can change it using JavaScript access, which will change globally as well...
But how to declare them...
It's quite simple:
For example, you wanna assign a #ff0000 to a var(), just simply assign it in :root, also pay attention to --:
:root {
--red: #ff0000;
}
html, body {
background-color: var(--red);
}
The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS or SASS...
Also, here is a simple JavaScript script, which changes the red value to blue:
const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');
CSS itself doesn't use variables. However, you can use another language like SASS to define your styling using variables, and automatically produce CSS files, which you can then put up on the web. Note that you would have to re-run the generator every time you made a change to your CSS, but that isn't so hard.
You can try CSS3 variables:
body {
--fontColor: red;
color: var(--fontColor);
}
There's no easy CSS only solution. You could do this:
Find all instances of background-color and color in your CSS file and create a class name for each unique color.
.top-header { color: #fff; }
.content-text { color: #f00; }
.bg-leftnav { background-color: #fff; }
.bg-column { background-color: #f00; }
Next go through every single page on your site where color was involved and add the appropriate classes for both color and background color.
Last, remove any references of colors in your CSS other than your newly created color classes.
The 'Less' Ruby Gem for CSS looks awesome.
http://lesscss.org/
Yes, in near future (i write this in june 2012) you can define native css variables, without using less/sass etc ! The Webkit engine just implemented first css variable rules, so cutting edge versions of Chrome and Safari are already to work with them. See the Official Webkit (Chrome/Safari) development log with a onsite css browser demo.
Hopefully we can expect widespread browser support of native css variables in the next few months.
Do not use css3 variables due to support.
I would do the following if you want a pure css solution.
Use color classes with semenatic names.
.bg-primary { background: #880000; }
.bg-secondary { background: #008800; }
.bg-accent { background: #F5F5F5; }
Separate the structure from the skin (OOCSS)
/* Instead of */
h1 {
font-size: 2rem;
line-height: 1.5rem;
color: #8000;
}
/* use this */
h1 {
font-size: 2rem;
line-height: 1.5rem;
}
.bg-primary {
background: #880000;
}
/* This will allow you to reuse colors in your design */
Put these inside a separate css file to change as needed.
Sure can, sort of, thanks to the wonderful world of multiple classes, can do this:
.red {color:red}
.blackBack {background-color: black}
but I often end up combining them anyway like this:
.highlight {color:red, background-color: black}
I know the semantic police will be all over you, but it works.
I'm not clear on why you can't use PHP. You could then simply add and use variables as you wish, save the file as a PHP file and link to that .php file as the style sheet instead of the .css file.
It doesn't have to be PHP, but you get what I mean.
When we want programming stuff, why not use a programming language until CSS (maybe) supports things like variables?
Also, check out Nicole Sullivan's Object-oriented CSS.
You can group selectors:
#selector1, #selector2, #selector3 { color: black; }
You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off
dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.
//create the CSS JSON object with variables and styles
var myCSSObjs = {
cssVariables : {
primaryColor:'#FF0000',
padSmall:'5px',
padLarge:'$expr($padSmall * 2)'
}
'body' : {padding:'$padLarge'},
'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
'.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};
//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();
And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo
EDIT: This answer is no longer current. You should use CSS variables now.
Consider using SCSS. It's full compatible with CSS syntax, so a valid CSS file is also a valid SCSS file. This makes migration easy, just change the suffix. It has numerous enhancements, the most useful being variables and nested selectors.
You need to run it through a pre-processor to convert it to CSS before shipping it to the client.
I've been a hardcore CSS developer for many years now, but since forcing myself to do a project in SCSS, I now won't use anything else.
If you have Ruby on your system you can do this:
http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html
This was made for Rails, but see below for how to modify it to run it stand alone.
You could use this method independently from Rails, by writing a small Ruby wrapper script
which works in conjunction with site_settings.rb and takes your CSS-paths into account, and
which you can call every time you want to re-generate your CSS (e.g. during site startup)
You can run Ruby on pretty much any operating system, so this should be fairly platform independent.
e.g. wrapper: generate_CSS.rb (run this script whenever you need to generate your CSS)
#/usr/bin/ruby # preferably Ruby 1.9.2 or higher
require './site_settings.rb' # assuming your site_settings file is on the same level
CSS_IN_PATH = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files')
CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' )
Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH )
the generate_CSS_files method in site_settings.rb then needs to be modified like this:
module Site
# ... see above link for complete contents
# Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory
# replacing any mention of Color Constants , e.g. #SomeColor# , with the corresponding color code defined in Site::Color
#
# We will only generate CSS files if they are deleted or the input file is newer / modified
#
def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') ,
output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets'))
# assuming all your CSS files live under "./public/stylesheets"
Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in|
filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') ))
# if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file:
if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime)
# in this case, we'll need to create the output CSS file fresh:
puts " processing #{filename_in}\n --> generating #{filename_out}"
out_file = File.open( filename_out, 'w' )
File.open( filename_in , 'r' ).each do |line|
if line =~ /^\s*\/\*/ || line =~ /^\s+$/ # ignore empty lines, and lines starting with a comment
out_file.print(line)
next
end
while line =~ /#(\w+)#/ do # substitute all the constants in each line
line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines
end
out_file.print(line)
end
out_file.close
end # if ..
end
end # def self.generate_CSS_files
end # module Site
Not PHP I'm afraid, but Zope and Plone use something similar to SASS called DTML to achieve this. It's incredibly useful in CMS's.
Upfront Systems has a good example of its use in Plone.
If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.
colors.xml:
<?xml version="1.0"?>
<colors>
<background>#ccc</background>
</colors>
styles.xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
<xsl:template match="/">body {
background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>
Command to render css: xsltproc -o styles.css styles.xsl colors.xml
styles.css:
body {
background-color: #ccc;
}
It’s not possible with CSS alone.
You can do it with JavaScript and LESS using less.js, which will render LESS variables into CSS live, but it’s for development only and adds too much overhead for real-life use.
The closest you can come with CSS is to use an attribute substring selector like this:
[id*="colvar-"] {
color: #f0c69b;
}
and set the ids of all your elements that you want to be adjusted to names starting with colvar-, such as colvar-header. Then when you change the color, all the ID styles are updated. That’s as close as you can get with CSS alone.

"Compile" CSS into HTML as inline styles

I am writing an e-mail HTML template, and some e-mail clients do not support <style> for specifying CSS. The only alternative for applying CSS is to use inline styles (style attribute). Is there a tool or library (Node.JS) for applying a stylesheet to some HTML and getting back the HTML with the styles applied?
The tool does not have to support many selectors; id, class, and element name selectors should be sufficient for my needs.
Example of what is needed:
// stylesheet.css
a { color: red; }
// email.html
<p>This is a test</p>
// Expected result
<p>This is a test</p>
I think juice is what you're looking for.
Simply require it, then pass it your html and css and let it do the heavy lifting for you like this:
var juice = require('juice');
var inlinedcss = juice('<p>Test</p>', 'p { color: red; }');
It builds on a number of mature libraries including mootools' slick, and supports a broad range of selectors.
You may also be interested in node-email-templates, which is a nice wrapper for dynamic emails in node.
Here's the alive javascript projects that does what you want:
juice. 1.7Mb with dependencies.
juice2. 5.9Mb with dependencies. This is a fork of juice, seems to be containing more options than juice. This one doesn't drop media queries as juice does. Sorts inline css rules alphabetically.
styliner. 4.0Mb with dependencies. This one uses promises instead. Have a couple of different options than juice2. Has a compact option that other ones don't have that minifies the html. Doesn't read the html file itself as others do. Also extends margin and padding shorthands. And in case you somehow modify your native objects(like if you are using sugar) I don't suggest using this till this issue is resolved.
So which one to use? Well it depends on the way you write CSS. They each have different support for edge cases. Better check each and do some tests to understand perfectly.
You could use jsdom + jquery to apply $('a').css({color:'red'});
2020 solution
https://www.npmjs.com/package/inline-css
var inlineCss = require('inline-css');
var html = "<style>div{color:red;}</style><div/>";
inlineCss(html, options)
.then(function(html) { console.log(html); });
Another alternative is to go back to basics. If you want a link to be red, instead of
my link
do
<font color="red">my link</font>
Almost any browser, including the terrible BlackBerry browser can handle that.