Class and ID Selectors
For the CSS Elementary Tutorial we analyzed only HTML selectors – the ones representing an HTML tag. You can also specify your own selectors that take the form of Class and ID selectors.
The advanatge of this is that you get the same HTML element, but present it in a different way based either on its class or ID.
In the CSS, a class selector appears as a name that follows a full stop (.
) and an ID selector appears as a name that follows a hash character (#
).
So the CSS might resemble the following code:
#top { background-color: #ccc; padding: 1em } .intro { color: red; font-weight: bold; }
The HTML is refered to the CSS by the means of the attributes id
and class
. It could take a similar form:
<div id="top"> <h1>Chocolate curry</h1> <p class="intro">This is my recipe for making curry purely with chocolate</p> <p class="intro">Mmm mm mmmmm</p> </div>
While the difference between an ID and a class is that an ID can be applied to specify one element, a class can be used to specify more than one element.
In addition, you can use a selector to a specific HTML element by just stating the HTML selector first, so p.jam { whatever }
will only be used with paragraph elements that have the class ‘jam’.