What is the difference between div#name and #name? Or is there a difference if you use class or id to position a certain element? Thank you
7 Answers
the first one is more specific if you have several rules applying for instance, in this example the first case "wins", since it is more specific.
div#kuku {color:red}
#kuku {color:blue}
A good source for reading: http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
Comments
div#name limits the selector to DIVs with the id only.
#name apples to any element with that id.
As @naivists points out, in case of a concurrency between two rules the more explicit one (div#name) wins.
1 Comment
# filters attribute "id", not "name"IDs are unique on a page and have more specificity. In other words, if you have
<div id="foo" class="bar">
Then
#foo{
background: green;
}
div#foo{
background: red;
}
.bar{
background: purple;
}
will be red. There is a good Specificity Wars explanation of this using Darth Vader and Star Wars here http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
Image here: http://www.stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg
In brief an ID # trumps any number of classes (.) which in turn trump any number of tag selectors. e.g:
# *beats* . . . . *beats* body div div ol li p