DEV Community

Cover image for Cascading what? Explanation about CSS Cascading rules
Nitsan Cohen
Nitsan Cohen

Posted on • Edited on

Cascading what? Explanation about CSS Cascading rules

CSS stands for Cascading Style Sheets

I want to talk with you about the cascading part today.

You probably already know that CSS is not a programming language. Instead, CSS is all about declaring rules to the elements in our DOM.

We have all kinds of ways to declare those rules.
For example, inline styles:

<div style="backgroundColor:red" class="my_div">Hi </div>
Enter fullscreen mode Exit fullscreen mode

Or class selectors:

.my_div {
background-color:green;
}
Enter fullscreen mode Exit fullscreen mode

But how do these rules apply? Which one is more powerful?

That is where the cascading rules come into action. The inline style will rule out the class selector in the example above.

I sometimes see people struggling with the cascading rules, but actually, it is straightforward.

When conflicting styles appear, the first thing your browser will check is the origin of the stylesheet.

We have two main types of origins:

-user-agent styles, which in simple words means browsers' default.
-Author styles, which in simple terms means - your custom styles.

The author styles will always override the user-agent styles.

So far, so good. But what if we have conflicts in the author styles themselves?

Well, it's effortless to remember that the winner is always inline styles.

After that, we get to the scary (and problematic to pronounce) word specificity.

Just memorize it: IDs, Classes, attributes, pseudo-classes, elements, pseudo-elements.

Or in symbols:

#id (avoid using them!)
.class (Classes).
h1[lang="pt"] (attributes).
h1: hover (pseudo-classes).
h1 (elements).
h1:: first-letter (pseudo-elements).
Enter fullscreen mode Exit fullscreen mode

Lastly, if no specificity rules apply, the browser will use the rule that appears later in the source.

I've created a nice diagram to help you with that. Please learn it by heart if you dare call yourself a frontend developer :)

css cascading rules

0h, and don't use !important (unless you have a significant reason).


  • For more posts like this follow me on LinkedIn

  • I work as frontend & content developer for Bit - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).

Top comments (0)