Classes and ID
So far, we have learned how to assign properties to elements.
In the previous section we restyled
the body, h1
and p elements.
That can be a bit restrictive, though: we may want to style more selectively.
Fortunately there are two HTML attributes that come to our aid here:
class and id.
class
The class attribute can be assigned to any element.
It can be used multiple times in a document. For example:
Don't try this at home!
</p>
You can then style all occurrences of elements of
class warning additionally to any styling
applied to unclassed occurrences of that element. This is done using
a dot to indicate class. You can either style specific elements of that class
(as in p.classname) or all elements given that class
(using .classname). Using the former method, we can style
the warning paragraph:
p.warning {
color: red;
font-weight: bold;
}
id
id works like class, but can
only be used once per document. At this stage, that may not seem too useful:
you’ll see the advantage when we get to positioning
divs later in the
tutorial.
In the CSS file, IDs are identifed with a hash (pound, octothorpe, sharp, whatever you want to call it—one of these: #).
[This site written by me]
</div>
#footer {
color: olive;
text-align: center;
}
So far, all of our colour examples have used simple colour names. There are several other ways to specify colours with a greater range of choice. Let’s move on and look at those now.