Reputation: 303
Is there any difference between this
#id {
}
and this
div#id {
}
Upvotes: 0
Views: 273
Reputation: 1523
#elementid selector will select all elements having the id "elementid"
On the other hand, div#elementid selector will select only divs having id "elementid"
Upvotes: 0
Reputation: 272036
The selectors behave differently:
#id
is same as writing *#id
(the asterisk selector is implied if tag name is omitted).
It matches any element that has an id of id
.
div#id
matches an element that is a div and has an id of id
.
It is more specific than the above example.
In general, using #id
selector is sufficient since ids are (supposed to be) unique inside a page. However, there are certain situations where you could use div#id
.
Example 1
You use different elements for similar purpose therefore you want to assign them same id but style them differently, then you must be more specific:
<!-- page 1 -->
<ul id="features" title="All amenities">
<li>Spa</li>
<li>Pool</li>
</ul>
<!-- page 2 -->
<ol id="features" title="Top 3 amenities">
<li>Spa</li>
<li>Pool</li>
</ol>
Example 2
You can add a tag name to add weight to your selector. Consider this example:
<div id="header">
<img>
<div id="logo"><img></div>
<img>
</div>
/* file 1 */
#logo img { border: thin solid; }
/* file 2 */
#header img { border: 0; }
The first rule adds a thin border to images inside logo, the other rule removes border from all images inside header (including the one inside logo). In order to force the thin border rule you can change it to div#logo img
so that it becomes more specific than the other rule.
Upvotes: 1
Reputation: 651
Short answer: Yes.
#id {}
targets a single ID selector wherever applied in a single HTML document. For example, <span id="id">...</span>
, or <p id="id">...</p>
div#id {}
will look for a <div>
element that has an ID of #id
, for example: <div id="id"></div>
and cannot be used on any other tag except a <div>
.
Note that ID selectors should only be used once semantically in a HTML document.
On a larger scale and more constructed case to this question, you should look at CSS Specificity; a well written and best-practise approach to specificity in CSS.
Also, take a look a CSSGuidelin.es, another well-written document on dealing with CSS selectors and their differences.
Upvotes: 0
Reputation: 700192
Yes. There is mainly two differences:
The first selector matches any element with id="id"
, while the second only matches div
elements with that id.
The second selector is more specific, so if you have both and they match the same element, the styles from the second will have precedence.
Normally you would use the first selector. As the id should be unique in the page it would only target a single element.
The second selector would be useful if you use the same style sheet for several pages, and you either want to target the id under certain conditions, or if you want to override another rule by making it more specific.
Upvotes: 4