Best way to select items with CSS

I have read all about the best order of selectors in CSS but I often (all the time) see people doing this....

nav ul li#email-me a {
   width: 120px;
   height: 43px;
   background: url(images/email_me.png) no-repeat top left;
   display: block;
}

From what I have read, my understanding is that this is better for performance...

#email-me a {
   width: 120px;
   height: 43px;
   background: url(images/email_me.png) no-repeat top left;
   display: block;
}

Am I missing something? Is the second method better? If it is, why does everybody use the first method?

Answers


I often use the first method, because

  • As mentioned in some other answers, it's more specific. An ID doesn't automatically make an entire rule more specific than any others forever; you can add a type selector — or pretty much anything except the universal selector * — to the ID and it'll immediately stomp out a rule with a lone ID selector. I don't find myself increasing a selector's specificity on purpose with this technique as much as I do it for organization, though...

  • To elaborate on organization: this kind of rule is often related to other rules that start with nav ul, and it helps to visually group them with a few initial selectors that are already in place.

    For example:

    nav ul {
        /* Styles for the ul */
    }
    
    nav ul li {
        /* Styles for the items */
    }
    
    nav ul li a {
        /* Styles for the item links */
    }
    
    /* 
     * If the selector here were just #email-me a, it'd be impossible
     * to see, right away, how it's related to the above rules, without
     * studying the markup that it applies to, and so on.
     */
    nav ul li#email-me a {
        /* Styles for the link in the #email-me item */
    }
    

The second method is supposedly faster because no additional checks need to be performed after identifying the ancestor element with the ID, but I have no benchmarks and I can't be bothered to make any.


Need Your Help

How to add an URL to Safari's reading list in iOS?

objective-c ios safari url-scheme

In my UIWebView I would like to add an option to add the current page to Safari's reading list.

Dynamic OnClick Button Event

javascript onclick dynamic-data

I have a table that is created dynamically, and I want to put an EDIT / DELETE buttons with onclick events in each row.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.