Adding Multiple CSS Classes to an Element

June 5th, 2011 - Posted by Steve Marks to (X)HTML / CSS, Web Development.

I find that CSS can generally be broken down into two categories; generic classes and element-specific classes. By doing this it makes the CSS less clunky and easier to maintain. Not sure what I mean? Let’s take a look at the following scenario:

Before

<style type="text/css">
    .elementOne { 
        border:1px solid #900; 
        text-align:center; 
    }
    .elementTwo { 
        border:1px solid #099; 
        color:#FFF; 
        text-align:center; 
    }
</style>

<div class="elementOne">foo</div>
<div class="elementTwo">bar</div>

The above is a very simple example, but notice how both elements use the ‘text-align’ attribute to center the text? Now imagine there are 100 elements on the page that require the text to be centered. That’s a lot of repeating CSS.

After

Now let’s take a look at the scenario above, but put the centering definition into it’s own class:

<style type="text/css">
    .elementOne { 
        border:1px solid #900; 
    }
    .elementTwo { 
        border:1px solid #099; 
        color:#FFF; 
    }
    .center {
        text-align:center; 
    }
</style>

<div class="elementOne center">foo</div>
<div class="elementTwo center">bar</div>

The above will show exactly the same output but means that we can now use the new ‘center’ class anytime we need text to be centered. Simply separate the class names with spaces and we can apply multiple classes to an element.

Tags:
This entry was posted on Sunday, June 5th, 2011 at 5:18 am by +Steve Marks and is filed under (X)HTML / CSS, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first