DEV Community

Cover image for CSS Cascade, Selector and Specificity.
Adepoju Ronke
Adepoju Ronke

Posted on • Updated on

CSS Cascade, Selector and Specificity.

The backbone of website development includes HTML, CSS and a programming language, which JavaScript take lead out of many. HTML basically deal with the content on the website while CSS focus on styling the content to make it appealing and JavaScript focus on functionality. Lets look into CSS, to start with, CSS stands for Cascading Styling Sheet and the topic is to explain CSS Cascade, CSS Selector and CSS Specificity. Lets go
CSS Cascading is set of rules that matters to the result you get. If two rules are set to a particular tag which one will work depends on the rules.

CSS Selector is the way of selecting html elemnt, and styling it.
Ways include, tag selector, class selector, ID selector... e.t.c

p {
  text-align: center;
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

The above is element selector but what happens when we have something like this

<!DOCTYPE html>
<html>
<head>
<style>
.center{
  text-align: center;
  color: red;
}
</style>
</head>
<body>

<h1 class="center">This heading will be red and center-aligned</h1>
<p class="center">This paragraph will be red and center-aligned.</p> 

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

but if i want to it to take effect on P alone, then we have it as

p {
  text-align: center;
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

The above is element selector but what happens when we have something like this

<!DOCTYPE html>
<html>
<head>
<style>
p.center{
  text-align: center;
  color: red;
}
</style>
</head>
<body>

<h1 class="center">This heading will not be affected</h1>
<p class="center">This paragraph will be red and center-aligned.</p> 

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The H1 is not affected because of more specification given to the selector.

CSS Specificity is selecting with more specification which you want to style having the rule in mind(Cascading). It what give priority to which rules to be override when we have more than one to rule to an element, just like the example above.

The specificity can be calculated by you and this helps you to know what and what is working or not working from the code you wrote, to calculate this type of selectors and how you combine it caries weight. Check this Specificity Calculator, need some help? check this out.

If you find this helpful, leave a comment. Also, have any opinion or contribution drop it in comment section. Thanks

Top comments (0)