CSS Selectors

The Class selector

The class selector can be used when we want more than one type of a particular element. For example, we might want a way to style some paragraphs in red text and some in blue. In this case all we need to do is specify two paragraph classes.

Within our HTML code we assign a particular class by using the class attribute within our tag. For the example above we could assign a red or blue paragraph by using one of the following:

<p class="red">Red text goes here</p>
<p class="blue">Blue text goes here</p>

We then need to set up two different style declarations within our CSS, like so:

p.red {color: red}
p.blue {color: blue}

One useful feature is that we can still assign values to the more general <p> tag and this will filter down into both our p.red and p.blue classes. This means that we can specify any common properties, such as font face and size, in our <p> tag, and just save the color properties for our more specific style declarations.

The id selector

The id selector is perfect when we have had to create our own tag using either <span> or <div>. If you cast your mind back to the HTML tutorial you may remember we specified these tags using an id attribute, such as <span id="red">. Well, we can use that id attribute to alter the styling.

id selectors are specified slightly differently than class selectors - by writing the id name, with a # in front, like so:

#red {color: red}

This would change the font color of the red span tag, so that whenever we use <span id="red"> in our HTML, the text that the tag surrounds will be styled as desired. The id selector can be used in exactly the same way to add styling to the <div> block-level tag.

Ok, so now we know how to structure our CSS styles, let's move on to see how we can apply them to our web pages.