How to Consolidate CSS Rules
If you're just learning CSS, you may be a victim of a common CSS newbie mistake--writing essentially the same rule over and over again for different selectors. This article will show you how to consolidate similar CSS rules.
Instructions
-
-
1
When you begin a stylesheet you may create a rule for each HTML element as you add it to a page or decide you want to style it. This can lead to style rules that essentially repeat the same thing again and again. For example:
h1 {font-family: Arial, Helvetica, sans-serif;}
h2 {font-family: Arial, Helvetica, sans-serif;}
p {font-family: Arial, Helvetica, sans-serif;}
li {font-family: Arial, Helvetica, sans-serif;} -
2
In the case of the example in Step 1, the simplest way to consolidate the font-family rules is to use the body selector like this:
body {font-family: Arial, Helvetica, sans-serif;}
Now everything will be the font-family you want (unless you specify otherwise for certain elements).
-
-
3
Another common CSS declaration that gets repeated often is about color. For example:
h1 {color: #333;}
h2 {color: #333;}
h3 {color: #333;}
h4 {color: #333;} -
4
The way to consolidate rules like the previous example is to use a comma separated list of selectors, like this:
h1, h2, h3, h4 {color: #333;}
- 5
- 6
-
7
Another way to consolidate is with descendant selectors. For example, instead of applying a class called "bodytext" to every paragraph in the section of your page that you consider the main body, use a descendant selector. Suppose the main body section of your page is a div called "content." In the style sheet, write a rule for:
#content p {some rule}
and it will automatically be added to every paragraph that you want to be a certain style of "bodytext."
-
1
Comments
-
DreamLiving
Aug 24, 2008
Another great article. Thanks. -
DreamLiving
Aug 24, 2008
Another great article. Thanks.