开发者

Difference between div#test and #test in CSS

Is开发者_运维百科 there a difference between div#test and #test selector in CSS?

How does it help to add 'div' before the id? Which method is recommended?


Use

#test

to specify a rule for any element with the single unique id, 'test'. There is always one unique id on 1 page.

If your stylesheet is shared between multiple HTML documents where the id test can have different meanings like

div#test OR p#test

declare the tagname as well.


Aside from div#test only matching <div> elements, it also has a higher specificity than #test, so where you have the following code:

div#test { color: green; }
#test { color: red; }

... the colour of #test would be green, assuming it is a <div> element. However, specificity isn't normally required with ID selectors, since they're required to be unique, unless there is a possibility it may move between ancestors or may be applied to different elements.

In summary, use #test if the element will always be a static <div>.

See also:

  • Calculating a selector's specificity - w3.org
  • CSS Specificity (HTML Dog)


div#test only matches div elements with id 'test', #test matches any element with the id 'test'.


Taken and slightly modified from How do I make a class take precedence over an ID

<div id="container" class="wrapper">
    <div id="normal" class="wider">
</div>

For this HTML snippet some possible selectors in decreasing order of specificity would be:

CSS Selector         -> Specificity
---------------------------------------
#container #normal   -> 0,2,0,0
#container .wider    -> 0,1,1,0
#normal.wider        -> 0,1,1,0
div#normal           -> 0,1,0,1 // this is the case you're asking about
#normal              -> 0,1,0,0
.wrapper .wider      -> 0,0,2,0
.wider               -> 0,0,1,0

Since ID's are unique (per page,) you're getting into esoteric CSS where you'd ever need to worry about the difference between div#test and #test--as Caspar Kleijne mentioned, a CSS document for multiple pages is probably the most likely scenario.

div.test vs. .test is a more likely scenario however, since you'll be able to wield class specificity much easiest on any given page.


div#test matches a div with the id="test". #test is matching any element with the id="test". Id's are basically stored in a hashtable/index and are direct lookups; it's not necessary to qualify them with an element.

So I would suggest sticking with #test.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜