As you can see from the previous page, it's fairly easy to specify rules which apply to each type of HTML element (level 1 heading, paragraph etc.). In many cases, however, you'll want to be able to apply different styles to different instances of an element. So, for example, you may want to make some paragraphs stand out by using larger, red text, while leaving other paragraphs unchanged. To be able to do this, you need to be able to identify these specific paragraphs, and apply different rules to them.
You can assign a class to HTML elements using the class attribute:
<p>This is a regular paragraph.</p> <p class="BigRed">This paragraph uses large, red text.</p> <p>This is another regular paragraph.</p> <p class="BigRed">This is another paragraph that uses large, red text.</p>
Your CSS file can then specify different rules for regular paragraphs, and paragraphs of the class "BigRed":
p {
font-family: Verdana;
font-size: 10pt;
text-align: justify;
}
p.BigRed {
font-size: 12pt;
color: red;
}
You can also make a class generic, so that it applies to multiple element types. In this example, we may also want to apply the "BigRed" class to other types of elements besides paragraphs (we might also want to apply it to headings, for example). To do this, we simply apply the same class to different types of elements:
<h1 class="BigRed">This heading uses large, red text.</h1> <p class="BigRed">This paragraph uses large, red text.</p>
In the CSS file, we remove the element part of the selector ("p"), so that the rule then applies to all elements of the "BigRed" class (headings, paragraphs, and anything else we apply it to):
.BigRed {
font-size: 12pt;
color: red;
}
Selecting by class does not always provide enough granularity - sometimes you want to be able to apply styles to a single instance of an element. You could, of course, create more and more granular classes. An alternative though is to use the id attribute to uniquely identify an element (IDs have to be unique within an HTML document, so they can't be used on multiple elements), and then apply styles to that id:
<p id="Paragraph_1">This paragraph has a unique ID.</p>
#Paragraph_1 {
color: blue;
}
<-- Previous Page CSS Structure |
Next Page --> Ext, Int and Inline Styles |