How To

How to Consolidate CSS Rules

Contributor
By Virginia DeBolt
eHow Contributing Writer
(2 Ratings)

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.

Difficulty: Moderately Easy
Instructions

Things You'll Need:

  • A text editor or CSS editor
  1. Step 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. Step 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. Step 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. Step 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. Step 5
    Too many classes in the HTML
    Too many classes in the HTML

    Sometimes, too much CSS gets added to the HTML code. The image gives an example.

  6. Step 6
    Save bandwidth with only one class in the HTML.
    Save bandwidth with only one class in the HTML.

    In the example in Step 5, the solution is to move the class designation to a higher level in the HTML. Using the list example, that could be the main list tag itself, as in the image.

  7. Step 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."

Comments  

Flag This Comment

on 8/24/2008 Another great article. Thanks.

Post a Comment

Post a Comment
  • Have you done this? Click here to let us know.
I Did This

Related Ads

Internet
Virginia DeBolt,

Meet Virginia DeBolt eHow's Internet Expert.

Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US

Demand Media
eHow_eHow Technology and Electronics