Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created September 10, 2024 12:42
Show Gist options
  • Save kingluddite/1fb8be74dd78704f45bdddeea0781346 to your computer and use it in GitHub Desktop.
Save kingluddite/1fb8be74dd78704f45bdddeea0781346 to your computer and use it in GitHub Desktop.
How does Specificity work in CSS?

In CSS, specificity determines which styles are applied when multiple CSS rules target the same HTML element. It’s like a ranking system that helps the browser decide which rule to use when there’s a conflict.

Basic Rule:

The more specific a rule is, the higher priority it has over other, less specific rules. CSS specificity is calculated based on the types of selectors used in a rule.

How Specificity Works:

Selectors in CSS can have different "weights" based on their type. The more specific a selector, the higher its weight, and the more likely it is to be applied over other styles.

Specificity Levels:

Here’s how different selectors contribute to specificity:

  1. Inline styles (e.g., style="color: blue") are the most specific and will override all other styles.
  2. ID selectors (e.g., #header) are very specific and have more weight than other types of selectors.
  3. Class selectors, attribute selectors, and pseudo-classes (e.g., .button, [type="text"], :hover) have medium specificity.
  4. Element selectors (e.g., div, p, h1) and pseudo-elements (e.g., ::before, ::after) have low specificity.

Specificity Calculation Example:

Consider the following rules:

/* Rule 1 */
h1 {
  color: red;
}

/* Rule 2 */
.header {
  color: blue;
}

/* Rule 3 */
#main-header {
  color: green;
}

If you have an <h1> element with the class .header and an ID #main-header, CSS will calculate specificity to determine which color to apply:

  1. h1 { color: red; } has the lowest specificity (element selector).
  2. .header { color: blue; } is more specific (class selector).
  3. #main-header { color: green; } is the most specific (ID selector).

In this case, the <h1> element will be green because the #main-header rule is the most specific.

Specificity Hierarchy:

  1. Inline styles: Highest specificity
  2. ID selectors: Higher specificity than classes and elements
  3. Class selectors, attribute selectors, pseudo-classes: Medium specificity
  4. Element selectors, pseudo-elements: Lowest specificity

Important Notes:

  • If two rules have the same specificity, the one that comes later in the CSS file will be applied.
  • !important can be used to force a style, but it should be avoided in most cases because it overrides normal specificity rules.

Understanding specificity is crucial for controlling the appearance of elements and debugging CSS when styles don’t seem to apply as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment