Hacker News new | past | comments | ask | show | jobs | submit login

The only reason id selectors would be faster (that I can think of) is that ids are supposed to be unique, so the matching can stop after finding the first element with an id. However, none of the browsers I tested this in actually did so. Here's an example:

http://jsfiddle.net/zsjrN/

Only the first paragraph should be red.




The only time I've known that the uniqueness of ids to be in play is either as a target of an anchor or to be used in Javascript. As far as I know, in those cases only the first element with that id will be involved.

Removing the CSS from your example, and then using Javascript to change the color you see that only the first one is altered.

http://jsfiddle.net/KQkJE/1/

So, in terms of CSS, it doesn't really matter. Well, I don't know about performance issues with it though. But for Javascript it matters a great deal. As for HTML, it only really matters in that it's supposed to be unique for anchor targets, which would be one reason it doesn't validate.

Browsers give a great deal of leeway when it comes to HTML and CSS, because so many people and editors do not follow the spec. Of course, you could argue that no one follows the spec because the browsers don't really enforce it. I've been constantly amazed over the years seeing various examples of HTML soup that should not render in any recognizable form that somehow renders in the browser.


There are a lot of "supposed to" rules in HTML and CSS that many people violate in practice, and browsers for the most part try to accomodate that if they can. Not surprised to hear that non-unique ids are permitted.


Ids are supposed to be unique but I don't think that browsers are supposed to assume that they are.


In practice, since so many web developers violate the rule about ids being unique, I think browser devs are forced to make the ID map into a multi-map, which makes it exactly the same as the class map.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: