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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With