Reputation: 1614
Recently I saw this on a CSS beginner's book (Beginning CSS Web Development By Simon Collison, Page 19)
h1#title{color:red;}
It is a element#id
structure.
But is this necessary? Since ID is unique in one html webpage, the element
is not necessary.
Is my understanding right?
Upvotes: 3
Views: 119
Reputation: 157334
id
are unique, but that doesn't mean they cannot be applied to other elements on different documents, so using something like #title
can be used ONLY ONE in one document, but can be used for other element in another document so though id
's are unique, you can use it on different elements on different documents. So using h1#title
will force the CSS to only apply on h1
element having id
#title
.
Also, specificity matters, h1#title
is more specific than #title
so using something like
#title {
color: red;
}
VS
h1#title {
color: green;
/* This will be picked regardless of their order in the stylesheet */
}
Upvotes: 5
Reputation: 1003
You are right. But, still this might be handy, when the programmer doesn't want to apply these styles, if someone changes h1
to some other tag like p
or h2
in html.
Upvotes: 1
Reputation: 239301
But is this necessary?
It can be, it's entirely context dependent.
It's extremely common for the same CSS file to be included in multiple pages, in which case the id isn't guaranteed to be unique. One page may have <h1 id="title">
and another page might have <div id="title">
, and you may only want to target one or the other.
It's up to you to decide if being more specific than #id
is warranted.
Upvotes: 2