The Cascade in CSS

The Cascade in CSS

Just launched! Checkout the CSS Course for Elementor users.

Table of Contents

Understanding how a browser renders your CSS styles requires a good grasp of Cascade in Cascading Style Sheets. If you've been reading user questions on the web relating to CSS, you've probably come across many developers wondering why the browser doesn't render some CSS styles.

More often than not, this hiccup has to do with the CSS cascade algorithm.

The cascading effect is an algorithm embedded in browsers. It decides the style to apply to every HTML element based on the provided CSS styles by the CSS engine, website visitors, and the web designer. The algorithm also resolves conflicts between styles targeting any given element.

For example, what happens when you have an element with an id and class and target it using different selectors? Consider the following illustration.

<p id="nice-id" class="cute-paragraph">Paragraph text here.</p>

You can target the element using different approaches, including the <p> tag, id, and class selectors like below.

p {
   color:blue;
}

#nice-id {
   color:red;
}

.cute-paragraph {
   color:pink;
}

The above CSS statements all target the example paragraph. They target the element using its tag, id, and class, respectively. What happens in such a case? What happens when the order of the statements is altered? How about where the element also has inline CSS?

In the following Code Playground, we've changed the order of the style declarations in the different code snippets and given the second paragraph inline CSS.

.cascade-cd1 p {
   color:blue;
}

.cascade-cd1 #nice-id {
   color:red;
}

.cascade-cd1 .cute-paragraph {
   color:pink;
}
 
.cascade-cd1 #nice-id {
   color:red;
}

.cascade-cd1 .cute-paragraph {
   color:pink;
}

.cascade-cd1 p {
   color:blue;
}
  
.cascade-cd1 .cute-paragraph {
   color:pink;
}

.cascade-cd1 p {
   color:blue;
}

.cascade-cd1 #nice-id {
   color:red;
}

Paragraph text here.

Paragraph text here.

You can see that the color of the first and second paragraphs didn't change in all the above three CSS snippets.

Why? The cascading effect in CSS.

The cascading effect algorithm considers, among other things, the order and position of a style, the specificity of the selection, the origin of the styling, and the level of importance of that given style.

Let's have a look at these in detail.

Importance

Element.how also provides premium tutorials showing awesome advanced designs, check them out here.

Looking for something else? Search across 2445 Elements right here:

Checkout the Elementor Addon Finder directly

Comments

Leave a Reply