Sobes.tech
Middle

Tell me about the levels of specificity (cascade) in CSS.

sobes.tech AI

Answer from AI

In CSS, specificity is a mechanism that determines which style rule will be applied to an element when multiple rules conflict.

Specificity levels can be represented as weights, which are calculated from different parts of the selector:

  1. Inline styles (e.g., style="...") have the highest priority.
  2. ID selectors (#id) give a high weight.
  3. Classes, pseudo-classes, and attributes (.class, :hover, [type="text"]) have a medium weight.
  4. Type selectors and pseudo-elements (div, ::before) have a low weight.

Example of calculating specificity:

  • #header .menu li a:hover — 1 ID + 2 classes/pseudo-classes + 2 tags = (1,2,2)
  • .menu li a — 0 ID + 1 class + 2 tags = (0,1,2)

The higher the specificity, the higher the priority of the rule. If specificity is equal, the rule declared later wins.

Example:

#id { color: red; }       /* specificity 1,0,0 */
.class { color: blue; }   /* 0,1,0 */
div { color: green; }     /* 0,0,1 */

<div id="id" class="class">Text</div>  /* color will be red */

Thus, cascade is not only about the order of rules but also their specificity, which determines which rule will be applied.