HTML and CSS Reference
In-Depth Information
The id attribute
Because you've already used ids on <a> elements, and because you already know how
to use a class attribute, you're not going to have to learn much to use the id attribute.
Say you have a footer on your page. There's usually only one footer on any page, so that
sounds like the perfect candidate for an id . Here's how you'd add the identifier footer to
a paragraph that contains the footer text:
Sim ilar to a c lass; just a dd th e
Unlike a class, yo u can only
have one element in your
page with an id o f “footer”.
at tribut e “id ” and choo se a
un ique i d nam e.
<p id="footer"> Please steal this page, it isn't copyrighted in any way </p>
N o spaces or speci al characters
ar e allowed in id n ames.
Giving an element an id is similar to adding an element to a class. The only differences are
that the attribute is called id , not class ; an element can't have multiple ids; and you can't
have more than one element on a page with the same id.
Q: What's the big deal? Why do I need an id just
to prove something is unique on the page? I could
use a class exactly the same way, right?
A: Well, you can always “simulate” a unique id with
a class, but there are many reasons not to. Say you're
working on a web project with a team of people. One
of your teammates is going to look at a class and think
it can be reused with other elements. If, on the other
hand, she sees an id, then she's going to know that's
for a unique element. There are a couple of other
reasons ids are important that you won't see for a few
chapters. For instance, when you start positioning
elements on a page, you'll need each element you
want to position to have a unique id.
Q: Can an element have an id and also belong
to a class?
A: Yes, it can. Think about it this way: an id is just
a unique identifier for an element, but that doesn't
prevent it from belonging to one or more classes (just
like having a unique name doesn't prevent you from
joining one or more clubs).
Search WWH ::




Custom Search