tags:

views:

113

answers:

7

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

+4  A: 

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/

naivists
+1  A: 

Class selectors can apply to many tags, while an id is uniquely associated with a single tag. So I'd say that a class selector will return multiple elements, while an id selector would return one.

duffymo
+1  A: 

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.

Pekka
`#` filters attribute "id", not "name"
Alex Bagnolini
Of course, thanks. Edited.
Pekka
A: 

div#name will match

<div id="name">foo</div>

but not

<span id="name">foo</span>

#name will match both, but you cannot have both in the same document as IDs are unique in the document, and classes can be multiple.

Fabien Ménager
+3  A: 

You use IDs for elements that appear once in the document. You use classes for more than one elements in the page.

What is the difference between div#name and #name?

div#name

refers to only that div which has id 'name'

while #name refers to any element having id 'name'

Sarfraz
+1  A: 

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%5Fspecificity%5Fwars.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
Gazzer
A: 

As for positioning, you generally have a number of elements with a given classname but id is specific to a single element. You generally do not want to position a number of elements at the same time, unless it is for only 1 axis.

unomi