I have three big CSS files which have many classes. Same of those classes have the same name but are in different files.
Example:
CSS1:
...
.btn-primary {
background: #000;
}
...
CSS2:
...
.btn-primary {
background: #fff;
}
...
and CSS3:
...
.btn-primary {
background: #4285F4;
}
...
Let's assume that all three CSS are called in my HTML page.
Is there a way to select in my web page only the .btn-primary class from CSS3? If yes, how could I do it?
No.
If a stylesheet is loaded into a page, and it has a ruleset with selector that matches an element, then it will apply to that element.
Rules which provide conflicting information for a particular property will overwrite each other in the standard cascade order.
Not as is, but you could alter your style sheets so that it reads like this:
.btn-primary, .btn-primary.style1 { ... }
.btn-primary, .btn-primary.style2 { ... }
.btn-primary, .btn-primary.style3 { ... }
Then you could get the specific styles by using the following class:
<a class='btn-primary style2'>Stylesheet 2</a>
In short, you'll need to add some sort of additional method of narrowing down the different styles.
--
Another possibility would be to convert your css files to scss like so:
.style1 {
.btn-primary { ... }
}
You could then use the styling from specific sheets like so:
<div class='style1'>
<a class='btn-primary'>Stylesheet 1</a>
</div>
An apologetic into: the following is, in my opinion, a wrong solution. I wanted to add it as I can think of situations where you have to find this kind of hacky ways rather than change the css files.
Generally speaking, as Quentin and Bryant pointed out - there is no "namespacing" for css files and so if you load all the css files you will end up with the last overriding file's selector classes (among the name-conflicted ones) and won't be able to choose between them.
If (for some odd reason) you don't care about Chrome users - you can probably use the cssRules or rules properties of the document.styleSheets[i] object - for each loaded stylesheet file (i being the number of the file). As noted, this method does not work for Chrome. Fore some reason both cssRules and rules are null in Chrome for each of the styleSheets[i].
My hacky solution:
After loading all the css files as you need,
In javascript code, read the css file you choose as a text file. You can use AJAX for that - see this question and its answers
Search for the selector you want in the text you got and extract that string. You can parse the whole file for example and take the relevant part.
In searching how to help with this step I came across the document.styleSheets[i].cssRules object and the method that doesn't work in Chrome.
Build a style element around it and append that style element to the head element (here's an answer that shows how to create and append style elements to the head element).
This seems like a wrong way to do it from several reasons (performance, elegance, readability) - and probably means the design of the css files is not right for your project (look at Bryant's suggestions) - but I wanted this answer to be here, as there is a way to do it, albeit a hacky one, and if for some reason you can't change the css files and have to use them as is - then here you go.
I don't know what is the usage of this, I mean having three files and storing different styles and even same styles into them.
But there are some tools that will normalize and minify your CSS, for example, take a look at Nano CSS
But, as other answers says it is not possible to say what class from what file apply to this page, and they will overwrite and the last style will apply for the element.
Here is also an example to find out how overwrite works:
#test-link {
display: block;
text-decoration: none;
background: red;
color: white;
}
#test-link {
background: green;
}
#test-link {
background: orange;
}
#test-link {
background: black;
}
<a id="test-link" href="javascript:void(0);">Test link</a>
As you see, just the last style applied for the background color
Related
I have a HTML5 page which has a master css and tabbed layout. Some tabs have 3rd party controls (like bootstrap.css etc ) which gets loaded when that tab is clicked resulting in overriding some of the properties of styles set by master.css
We can solve this issue by not allowing those particular properties to NOT get overridden by !important. But we have 1000's of such properties and may not be possible to do it manually for all.
Any workaround for this?
As mentioned in one of the comments, you can use something called as CSS specificity to solve the problem.
You can read more about it here.
To be brief, make the more important styles more specific.
For example:
.my-divs .green {
color: green;
}
receives more priority then
.green {
color: green;
}
I am working with Drupal and with that, I don't always have the freedom to add a class by altering a html tag, however. I would like to apply some Twitter Bootstrap styling on an element from my custom.css file (the bootstrap css file is loaded, so styling is available).
To illustrate it better, for example, I would like to apply class="img-polaroid" (TB base styling) to an image that I can interface as div.someClass in my custom css stylesheet. I don't have simple way to alter the img tag to have class="img-polaroid someClass".
I would like to accomplish the same in my custom stylesheet. In another words, the merge happens not in the html tag but in the css stylesheet itself. How can I accomplish this with the current technologies in place? Are we there to make this possible?
Thank You
p.s. I am aware of alternatives:
-use JS to append class
-Copy and past the styling of class="img-polaroid" into div.someClass {...}
But both seem like not so nice solutions
How you go about this depends on which CSS Preprocessor you're using. You must choose one if you want to avoid modifying TB itself or the markup.
Sass
.foo {
#extend .bar;
}
Output:
.bar, .foo {
// styles
}
LESS
.foo {
.bar;
}
Output:
.bar {
// styles
}
.foo {
// styles
}
You can locate the part of the CSS code that you want to apply to the element in the bootstrap stylesheet and rewrite the selectors or copy the code to another file with new selectors so the style applies to both
.selector-from-bootrap,
.my-new selector{
...
}
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Avoiding repeated constants in CSS
We have some "theme colors" that are reused in our CSS sheet.
Is there a way to set a variable and then reuse it?
E.g.
.css
OurColor: Blue
H1 {
color:OurColor;
}
There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around:
/* Theme color: text */
H1, P, TABLE, UL
{ color: blue; }
/* Theme color: emphasis */
B, I, STRONG, EM
{ color: #00006F; }
/* ... */
/* Theme font: header */
H1, H2, H3, H4, H5, H6
{ font-family: Comic Sans MS; }
/* ... */
/* H1-specific styles */
H1
{
font-size: 2em;
margin-bottom: 1em;
}
This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect.
Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values.
You can achieve it and much more by using Less CSS.
No, but Sass does this. It's a CSS preprocessor, allowing you to use a lot of shortcuts to reduce the amount of CSS you need to write.
For example:
$blue: #3bbfce;
$margin: 16px;
.content-navigation {
border-color: $blue;
color:
darken($blue, 9%);
}
.border {
padding: $margin / 2;
margin: $margin / 2;
border-color: $blue;
}
Beyond variables, it provides the ability to nest selectors, keeping things logically grouped:
table.hl {
margin: 2em 0;
td.ln {
text-align: right;
}
}
li {
font: {
family: serif;
weight: bold;
size: 1.2em;
}
}
There's more: mixins that act kind of like functions, and the ability to inherit one selector from another. It's very clever and very useful.
If you're coding in Ruby on Rails, it'll even automatically compile it to CSS for you, but there's also a general purpose compiler that can do it for you on-demand.
You're not the first to wonder and the answer is no. Elliotte has a nice rant on it: http://cafe.elharo.com/web/css-repeats-itself/. You could use JSP, or its equivalent, to generate the CSS at runtime.
CSS doesn't offer any such thing. The only solution is to write a preprocessing script that is either run manually to produce static CSS output based on some dynamic pseudo-CSS, or that is hooked up to the web server and preprocesses the CSS prior to sending it to the client.
That's not supported at the moment unless you use some script to produce the CSS based on some variables defined by you.
It seems, though, that at least some people from the browser world are working on it. So, if it really becomes a standard sometime in the future, then we'll have to wait until it is implemented in all the browsers (it will be unusable until then).
Since CSS does not have that (yet, I believe the next version will), follow Konrad Rudolphs advice for preprocesing. You probably want to use one that allready exists: m4
http://www.gnu.org/software/m4/m4.html
You're making it too complicated. This is the reason the cascade exists. Simply provide your element selectors and class your color:
h1 {
color: #000;
}
.a-theme-color {
color: #333;
}
Then apply it to the elements in the HTML, overriding when you need to use your theme colors.
<h1>This is my heading.</h1>
<h1 class="a-theme-color">This is my theme heading.</h1>
I've written a macro (in Visual Studio) that allows me to not only code CSS for named colors but to easily calculate shades or blends of those colors. It also handles fonts. It fires on save and outputs a separate version of the CSS file. This is in line with Bert Bos's argument that any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation.
The full setup along with all the code would be a bit too complicated to post here, but might be appropriate for a blog post down the road. Here's the comment section from the macro which should be enough to get started.
The goals of this approach are as follows:
Allow base colors, fonts, etc. to be defined in a central location, so that an entire pallete or typographical treatment can be easily tweaked without having to use search/replace
Avoid having to map the .CSS extension in IIS
Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode
Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested
Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow
With this approach, colors, shades of colors, and font families are all represented with shorthand tokens that refer to a list of values in an XML file.
The XML file containing the color and font definitions must be called Constants.xml and must reside in the same folder as the CSS files.
The ProcessCSS method is fired by EnvironmentEvents whenever VisualStudio saves a CSS file. The CSS file is expanded, and the expanded, static version of the file is saved in the /css/static/ folder. (All HTML pages should reference the /css/static/ versions of the CSS files).
The Constants.xml file might look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<cssconstants>
<colors>
<color name="Red" value="BE1E2D" />
<color name="Orange" value="E36F1E" />
...
</colors>
<fonts>
<font name="Text" value="'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif" />
<font name="Serif" value="Georgia,'Times New Roman',Times,serif" />
...
</fonts>
</cssconstants>
In the CSS file, you can then have definitions like:
font-family:[[f:Text]];
background:[[c:Background]];
border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */
See also Avoiding repeated constants in CSS. As Farinha said, a CSS Variables proposal has been made, but for the time being, you want to use a preprocessor.
You can use mutliple classes in the HTML element's class attribute, each providing part of the styling. So you could define your CSS as:
.ourColor { color: blue; }
.ourBorder { border: 1px solid blue; }
.bigText { font-size: 1.5em; }
and then combine the classes as required:
<h1 class="ourColor">Blue Header</h1>
<div class="ourColor bigText">Some big blue text.</div>
<div class="ourColor ourBorder">Some blue text with blue border.</div>
That allows you to reuse the ourColor class without having to define the colour mulitple times in your CSS. If you change the theme, simply change the rule for ourColour.
This may sound like insanity, but if you are using NAnt (or Ant or some other automated build system), you can use NAnt properties as CSS variables in a hacky way. Start with a CSS template file (maybe styles.css.template or something) containing something like this:
a {
color: ${colors.blue};
}
a:hover {
color: ${colors.blue.light};
}
p {
padding: ${padding.normal};
}
And then add a step to your build that assigns all the property values (I use external buildfiles and <include> them) and uses the <expandproperties> filter to generate the actual CSS:
<property name="colors.blue" value="#0066FF" />
<property name="colors.blue.light" value="#0099FF" />
<property name="padding.normal" value="0.5em" />
<copy file="styles.css.template" tofile="styles.css" overwrite="true">
<filterchain>
<expandproperties/>
</filterchain>
</copy>
The downside, of course, is that you have to run the css generation target before you can check what it looks like in the browser. And it probably would restrict you to generating all your css by hand.
However, you can write NAnt functions to do all sorts of cool things beyond just property expansion (like generating gradient image files dynamically), so for me it's been worth the headaches.
CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.
Here are two major approaches to achieve more dynamic style handling:
Server-side variables in inline css
Example (using PHP):
<style> .myclass{color:<?php echo $color; ?>;} </style>
DOM manipulation with javascript to change css client-side
Examples (using jQuery library):
$('.myclass').css('color', 'blue');
OR
//The jsvarColor could be set with the original page response javascript
// in the DOM or retrieved on demand (AJAX) based on user action.
$('.myclass').css('color', jsvarColor);
I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle.
i.e.
.color1 {
color: #3d444d;
}
One thing I've done here is break out my palette declarations from other style/layout markup, grouping commonly-colored items in lists, e.g.
h1 {
padding...
margin...
font-family...
}
p {
...
}
code {
...
}
/* time passes */
/* these elements are semantically grouped by color in the design */
h1, p, code {
color: #ff0000;
}
On preview, JeeBee's suggestion is a logical extension of this: if it makes sense to handle your color declarations (and, of course, this can apply to other style issues, though color has the unique properties of not changing layout), you might consider pushing it out to a separate css file, yeah. This makes it easier to hot-swap color-only thematic variations, too, by just targeting one or another colorxxx.css profile as your include.
That's exactly what you should do.
The more centralized you can make your css, the easier it will be to make changes in the future. And let's be serious, you will want to change colors in the future.
You should almost never hard-code any css into your html, it should all be in the css.
Also, something I have started doing more often is to layer your css classes on eachother to make it even easier to change colors once... represent everywhere.
Sample (random color) css:
.main_text {color:#444444;}
.secondary_text{color:#765123;}
.main_color {background:#343434;}
.secondary_color {background:#765sda;}
Then some markup, notice how I am using the colors layer with otehr classes, that way I can just change ONE css class:
<body class='main_text'>
<div class='main_color secondary_text'>
<span class='secondary color main_text'>bla bla bla</span>
</div>
<div class='main_color secondary_text>
You get the idea...
</div>
</body>
Remember... inline css = bad (most of the time)
See: Create a variable in .CSS file for use within that .CSS file
To summarize, you have three basic option:
Use a macro pre-processor to replace constant color names in your stylesheets.
Use client-side scripting to configure styles.
Use a single rule for every color, listing all selectors for which it should apply (my fav...)
I sometimes use PHP, and make the file something like style.css.php.
Then you can do this:
<?php
header("Content-Type: text/css");
$colour1 = '#ff9';
?>
.username {color: <?=$colour1;?>; }
Now you can use that colour wherever you want, and only have to change it in one place. This also works for values other then colours of course.
Maybe pull all the color information into one part of your stylesheet. For example change this:
p .frog tr.mango {
color: blue;
margin: 1px 3em 2.5em 4px;
position: static;
}
#eta .beta span.pi {
background: green;
color: red;
font-size: small;
float: left;
}
// ...
to this:
p .frog tr.mango {
color: blue;
}
#eta .beta span.pi {
background: green;
color: red;
}
//...
p .frog tr.mango {
margin: 1px 3em 2.5em 4px;
position: static;
}
#eta .beta span.pi {
font-size: small;
float: left;
}
// ...
You could have a colours.css file with just the colours/images for each tag in.
Then you can change the colours just by replacing the file, or having a dynamically generated CSS file, or having different CSS files available and selecting based upon website URL/subfolder/property/etc.
Or you can have colour tags as you write, but then your HTML turns into:
<p style="body grey">Blah</p>
CSS should have a feature where you can define values for things like colours that you wish to be consistent through a style but are defined in one place only. Still, there's search and replace.
So you're saying you don't want to go back into your CSS to change color values if you find another color 'theme' that might work better?
Unfortunately, I don't see a way around this. CSS defines styles, and with color being one of them, the only way to change it is to go into the css and change it.
Of course, you could build yourself a little program that will allow you to change the css file by picking a color wheel on a webpage or something, which will then write that value into the css file using the filesystemobject or something, but that's a lot more work than required for sure.
Generally it's better to just find and replace the colours you are changing.
Anything more powerful than that will be more complex with few benefits.
CSS is not your answer. You want to look into an abstraction on top of CSS like SASS. This will allow you to define constants and generally clean up your css.
Here is a list of CSS Frameworks.
I keep a list of all the colors I've used at the top of the file.
When the CSS is served by a server-side script, eg. PHP, usually coders make the CSS as a template file and substitute the colors at run-time. This might be used to let users choose a color model, too.
Another way, to avoid parsing this file each time (although cache should take care of that), or just if you have a static site, is to make such template and parse it with some script/static template engine before uploading to the server.
Search/replace can work, except when two initially distinct colors end up being the same: hard to separate them again after that! :-)
If I am not mistaken, CSS3 should allow such parametrization. But I won't hold my breath until this feature will be available in 90% of browsers surfing the Net!
I like the idea of separating the colour information into a separate file, no matter how I do it. I would accept multiple answers here if I could, because I like Josh Millard's as well. I like the idea of having separate colour rules though because a particular tag might have different colours depending on where it occurs. Maybe a combination of both of these techniques would be good:
h1, p, code {
color: #ff0000;
}
and then also have
.color1 {
color: #ff0000;
}
for when you need to restyle.
This is where SASS comes to help you.