Class Selectors

We learnt what ‘Element Selectors’ are and how to group declarations and selectors, in our tutorial Element Selectors in CSS. But as you advance in HTML and CSS, you will need more specialized rules to style an element.  Apart from document elements (element selectors) there are two other types of selectors you can define on your own. They are Class selectors and ID selectors.

What are class selectors?

A class selector is set of styles that you can apply to one or more elements. See these examples:

<p class=”desc_text” >Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor </p>

<h3> Lorem ipsum dolor <span class=”desc_text”> sit amet, consectetur adipisicing elit, sed </span> do eiusmod tempor </h3>

A class ‘desc_text’ when applied to the paragraph element stylizes the entire paragraph whereas when applied to the span element stylizes only the spanned text.

Though we will learn more about the ID selector later, the main difference between the two is that class selectors can be used for multiple selectors and ID selector can style a single element in the entire document.

Defining class selector in CSS

In CSS the class selector is preceded by a period ‘.’ followed by the class name and style definition. See below:

.desc_text {font-size: 10px; color: #cccccc; }

This kind of class selector could be applied to any element that matches the class attribute value ‘desc_text’.

You can also use the universal selector ‘*’ to define the class that matches any element in the document.

*.desc_text {font-size: 10px; color: #cccccc;}

But this one;

p.desc_text {font-size: 10px; color: #cccccc; }

will match any paragraph elements that have the class attribute containing the word ‘desc_text’. In the above example the span element would not match this class and hence the styles would not be applied. So this kind of rule applies only to a specific type of element.

Combination of general class selector and element-specific class selector

.desc_text { font-size: 10px; }

span.desc_text { color: #cccccc ;}

First declaration is an example of general class selector and the second one is of element specific class selector. You can declare both and use them together. The output of the above example would be as shown below:

Example

Filed Under: CSS Hacks, Tips and Tricks

Tags:

About the Author: Minal is a freelance web and graphics designer. She specializes in designing Logos, Stationery, Graphics and Icons as well as website templates using graphical tools like Photoshop, Illustrator and Expression Web. Twitter @saffronstroke

RSSComments (0)

Trackback URL

Leave a Reply