Using ids and classes
Ids and classes are used to distinguish certain HTML elements from other elements of the same type e.g. not all p
elements are created equal.
An example
Let’s say someone threatened us with bodily harm and told us to make a page using only p tags. We can do it! We can survive!
<p id="page-title">This can be a title</p>
<p class="headline first">This could be a headline</p>
<p>This is a paragraph tag</p>
<p class="headline second">This could be a headline</p>
<p>This is a paragraph tag</p>
<style>
#page-title {
font-size: 60px;
font-weight: bold;
}
.headline {
font-size: 24px;
font-family: "Comic Sans MS";
}
</style>
If we looked at this page, the first p
would be large and bold while the second and fourth p
s would be in Comic Sans. We’ve just used css selectors for id
s and class
es!
Four rules
- An
id
on an element should be unique over the entire page, a.k.a. no repeatingid
s. - A
class
can be repeated. - You can have multple classes, separated with a space.
class="headline second"
is the classheadline
and the classsecond
. - You select an
id
with a#
, and you select a class with a.
. Why? It’s just the rules.