Getting Specific About CSS Specificity

By admin

Javascript

Web Development

You likely already knew that some methods of styling will override others when you’re writing CSS…but do you know why?

For example, a style assigned to a class will be preferred over one applied to a base element. Here, the header with the class name will be red, even though we said h2s should all be blue. That’s because CSS weighs classes as more specific than elements, and therefore prefers the red style defined to the class.

<style>
h2 { color: blue; } 
.my-header { color: red; } 
</style> 

<h2 class="my-header">Hello World!</h2> 

We would read this specificity level as [0, 1, 1, 2]. That’s because there are no [0] inline styles in a CSS file, one [1] ID (the #nav), one [1] class (the .menu), and two [2] elements (the list and the anchor).

When two different styles are applied to the same thing, their specificity levels are compared and the higher one wins. So, in this case, if we wanted to override that example style, we could create another style that added another class [0, 1, 2, 2] – or, we could add an inline style in the HTML [1, 1, 1, 2]. And – for better or worse – !importants will trump everything, no contest.

You may be asking why we don’t just read these as numbers – in that example, one hundred and twelve versus one hundred twenty two or one thousand, one hundred and twelve. After all, if we think about this as a kind of base ten points system, we should just be able to add it all up and read the number from left to right…right?

Unfortunately, it’s not quite that easy. We use this particular notation because sometimes we’ll go over ten in any individual column – like if you were to put twelve classes on something. I don’t particularly encourage writing something that uses that many classes, but but hey – some of you are probably Tailwind users, right? 😉

If we had twelve classes, our specificity might look like [0, 0, 12, 1]. Just reading from left to right, we might be tempted to read that as one hundred and twenty one…but the specificity of something with twelve classes and an element would be different than something that had one ID, two classes, and one element: [0, 1, 2, 1] – which could also, arguably, be read from left to right as one hundred and twenty one. So, the commas are actually in place to discourage us from doing just that.

Share this article

Bài viết liên quan

How to Master Web Development in 2023
Career How to Master Web Development in 2023

Web development continues to evolve at a rapid pace. Staying current with the latest technologies, frameworks, and best practices is...

Subscribe to our Newsletter

Get the latest web development articles, tutorials, and resources straight to your inbox.

We respect your privacy. Unsubscribe at any time.