Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 606
JasonDavis Avatar asked Dec 22 '22 05:12

JasonDavis


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

like image 87
BoltClock Avatar answered Jan 07 '23 20:01

BoltClock