Hack Frontend Community

CSS Selector Specificity

CSS selector specificity determines which style will be applied when multiple selectors match the same element. The higher the specificity, the higher the style priority.

Specificity Formula

Specificity is calculated based on three categories
Important: The classical specificity counting system doesn't include !important, as it's a separate concept that overrides everything. Usually, we talk about three categories, but for completeness, !important can be mentioned as a special case:

  1. !important overrides all normal styles (separate from the specificity mechanism)
  2. Inline styles (embedded styles, e.g., style="color: red;") have the highest priority.
  3. IDs give a weight of 100 points each.
  4. Classes, attributes, and pseudo-classes add 10 points each.
  5. Tags and pseudo-elements add 1 point each.

Specificity Examples

SelectorSpecificityExplanation
*0, 0, 0Universal selector, minimum weight.
p0, 0, 1One tag (1 point).
.class0, 1, 0One class (10 points).
#id1, 0, 0One identifier (100 points).
div.class0, 1, 1One tag (1) and one class (10).
#id .class p1, 1, 1One ID (100), one class (10), one tag (1).
style="color: red;"Inline styleMaximum specificity.

How Specificity Works

When styles from different selectors are applied to an element, the selector with greater specificity is used. If specificity is equal, the style that appears later in the code is applied (cascade rule).


Example

<div id="example" class="box">
  Example text
</div>
/* Styles */

div { color: black; }          /* 0, 0, 1 */
.box { color: blue; }          /* 0, 1, 0 */
#example { color: red; }       /* 1, 0, 0 */

/* Final style: text color will be red (#example). */

Tip:

Avoid excessive use of ID selectors. This makes code less flexible and complicates style overriding.