The second key feature of CSS that makes it so powerful is Specificity. Specificity is how specific your selectors are. p {color: #000;} will make everything in <p> tags black, body p {color: #F00;} is more specific and it will make everything in <p> tags red no matter where the selector is called in the style sheet.
To make a CSS selector more specific add more HTML elements or attributes to the selector. p {color: #000;} selects all <p> tags, not very specific. To get more specific we can target the <div> the <p> tags are in (let’s pretend they are in a DIV with an ID of “Header”).
<div id="Header">
<p>This is the paragraph text.<p>
</div>
p {
color: #000;
}
#Header p {
color: #F00;
}
Everything in <p> tags will be black except for the stuff in the <p> tags inside <div id="Header">, that will be red. Specificity allows you to use less classes and IDs to target HTML elements. If you were using the “Header” div already for other purposes and you wanted only the <p> tags inside that div to be red, why add another class when you can just get more specific?
Here’s a crazy example that shows you just how you’d avoid writing out a bunch of CSS just to change one property of one tag in one div.
Let’s pretend you want everything in <p> tags to be black and 12px big with a padding of 5px and a line height of 24px. You also want everything in <p> tags in the “Header” div to be red and everything in <p> tags in the “Footer” div to be white. Instead of writing the font size, padding and line height out 3 times, just do it once and use specificity to change the other colours.
p {
color: #000;
font-size: 12px;
padding: 5px;
line-height: 24px;
}
#Header p {
color: #F00;
}
#Footer p {
color: #FFF;
}
Everything in <p> tags in the “Header” and “Footer” divs will keep the padding, font size and line height but the colour will be over-written because those selectors are more specific.
Specificity will save you time and bytes. It will make your CSS easier to follow and it will prove to all of your friends that you understand CSS better than them.
Yo man, this is exactly what I needed! Some cool way to prove to all my friends that I do understand CSS better than them! Also, since we are on the topic of cool ways to outdo my friends, I should also tell them about my cool apartment, girlfriend, and my super cool dog. Except for one small problem; I have no friends. I suspect that you don’t either. We could be friends.
Good article btw!
Haha, thanks.