I have encountered a couple situations recently in working with clients that are writing their own CSS. By looking at their code, I can see that they don't completely understand how CSS works, because they are writing
too much code. So I decided a blog post on this topic was necessary.
The beauty of Cascading Style Sheets is their ability to
cascade. Basically, when you have several style sheets, the last one to be read into the page is going to have the most importance, but all files will still be read. Certain parts of the less important files are just overridden.
So let's say in one CSS file you have the following attributes set for paragraph text:
p {
color: #000000;
font-size: 12px;
line-height: 16px;
}
This file is called into your document by putting this code in the <head>:
<style type="text/css" media="all">@import url("first.css");</style>
Now you have a second file you want to import, and it has these attributes for your paragraphs:
p {
color: #4c4c4c
margin: 0;
padding: 0 0 15px 0;
font-weight: normal;
}
And this second file is now added to your list of imported stylesheets:
<style type="text/css" media="all">@import url("first.css");</style>
<style type="text/css" media="all">@import url("second.css");</style>
All attributes will be read in from first.css, then second.css. Color is listed in both, so since second.css is listed last, it's going to take the #4c4c4c value, overriding #000000. All other values listed in first.css will still apply to the paragraphs. There is no need to duplicate the attributes listed in first.css into second.css.
More
To go into this a little bit further -- let's add a class called "bodyText" to that paragraph. Since it's still a paragraph, all the CSS listed above will apply. But now you can add more CSS that is specific to your bodyText:
.bodyText {
font-weight: bold;
border: 1px solid #123456;
}
Once again, the styles that have already been declared for paragraphs do not need to be duplicated.
Why?
Now why would you ever use multiple stylesheets? I'll give a simple example. Let's say you have a fairly large website, with three or four separate sections. You have one CSS file that will apply to the entire site. This will set things like page width and font. But now you want each section to have its own set of colors. This is where you can write a specific CSS file for each section. Each section will import the site-wide CSS, then that section's css.
A Matter of !Importance
Final note, I promise. If you were to go back to first.css and add !important next to the color (color: #000000 !important;), it is going to take precedence (unless, of course, second.css also had !important next to its color). I try to use this sparingly, especially since IE6 tends to ignore it.