How Cascading Is Done In CSS
CSS (cascading style sheet) is used to design website structure that is created by html according to the one’s need. In le-man language we can also say that CSS is used to do makeup of a web page. For targeting some tags or elements, we have some selectors in css like class, id, etc. We can also target an element through it’s tagname. For targeting elements, specifity algorithm is there which sets the priority of element according to the selectors. As much the specification increases, priority increases. For example, id is unique identifier but class can be common for more than one element, in this case id is more specific than class, so the priority of class is less than id.
<html>
<head>
<title>Cascading in CSS</title>
<style>
#blue{
color: blue;
}
.red{
color: red;
}
</style>
</head>
<body>
<div class="red" id="blue">I am red</div>
</body>
</html>
How It Works?
CSS rules can come from various sources such as user-defined styles, browser default styles and custom styles from a website. Cascading process determines which of these styles is applied when they conflict.
Specificity : The selector which is more specific have higher priority than the selector which is less specific. As in above case ‘id=”blue”‘ is applied rather than the ‘class=”red”’ because id is more specific than class.
Importance : Importance have highest priority over all the other rules. If !important is marked with the rule then it will be applied irrespective of any other thing.
Source Order : If multiple rules have the same specificity then the rule which is written after the first one will be applied because it will overwrite the first one.
Cascading Order Breakdown
Here is a simplified breakdown of the cascading order :
!important : Highest priority, regardless of source.
Inline : Next in priority, if it is not overwritten by !important.
Internal CSS : Styles in the <style> tag which only apply to that document.
External CSS : Styles from the external CSS linked to the html document, which apply globally accross multiple pages.
Browsers/User styles : Defaults or user-defined preferences.
CSS Specificity :
CSS specifity plays a huge role in cascading. It is the measure of how much a selector is specific, and it helps determine which rule is applied when multiple rules are for the same element.
Inline styles : 1000 points
Id selector : 100 points
Class, attributes, and pseudo class : 10 points
Tag and pseudo elements : 1 point
Overriding Rule
In CSS overriding rule comes in picture when more than one rule is applied on one element. The more specific rule or the last one wins over the others and applied on the element.
The first <p> tag is styled by the tag selector (style: color: red;) so it is red.
The second <p> tag is styled by the class selector, so it is blue.
The third <p> tag is styled by the id selector, and the class both but the id is more specific, so it is green.