0

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 7

4

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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'

Comments

1

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.

Comments

1

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"
1

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.