HTML and CSS Reference
In-Depth Information
• Count the number of type selectors and pseudo-elements in the selector
• Ignore the universal selector
IDs are deemed to be very specific (because they are unique to the page) and count as 100 points. Each class, attrib-
ute, and pseudo-class selector counts as 10 points, and each type or pseudo-element selector counts as 1 point.
So, out of the two selectors in the example, header#header > nav[role=”navigation”] gets 112 points
and nav gets only 1!
If the first rule should be more important than the other, I could be more sensible and just make it header nav
(giving it 2 points). This is better for performance and makes CSS more manageable in the future; plus, you can still
clearly see this rule is more specific, without going to the lengths of calculating specificity!
What if both rules are as specific as each other? For example:
nav {
color: red;
nav {
color: blue;
In this case, the latter rule always wins.
This attribution of importance is known as the cascade —where the C in CSS comes from.
The !important Rule
If you're the type of character who doesn't play by the rules and that's how you want your CSS to be, let me intro-
duce you to !important .
You've learned the rules of the cascade, but sometimes you might need to make a selector that has less specificity
more important than those with higher specificity.
The !important rule is ideal during development when you just want to see a style applied to the page, regardless
of specificity. It's arguable whether !important should be used in production at all because it's better for per-
formance that you respect the cascade. Here is a good use case, though:
.error {
color: red !important;
This approach tends to be used on dynamic sites. Imagine a contact form in which the user hasn't added all the re-
quired details. It's important that the color of the error message be red (above any other color potentially being ap-
plied to this element through other selectors) so that the user knows he's made a mistake and his eye is drawn to it.
The !important rule should start with an exclamation mark ( ! ) and be placed after a property value before the
closing semicolon.
Search WWH ::

Custom Search