CSS Specificity Cheat Sheet

Specificity in CSS determines which style rules are applied when there are conflicting styles targeting the same element. Here’s a cheat sheet to understand and calculate specificity:

Specificity Hierarchy

Inline Styles:

  • An inline style (inside an HTML element) has the highest specificity.
<div style="color: red;">This is red text</div>

ID Selectors:

  • ID selectors have higher specificity than class selectors and element selectors.
#unique-id {
  color: blue;
}

Class Selectors, Attribute Selectors, Pseudo-classes:

  • Class selectors, attribute selectors, and pseudo-classes have the same specificity.
.my-class {
  color: green;
}

[type="button"] {
  color: orange;
}

a:hover {
  color: purple;
}

Element Selectors:

  • Element selectors have lower specificity than class selectors, attribute selectors, and pseudo-classes.
p {
  color: yellow;
}

Combining Selectors

Combining Selectors:

  • The more specific a selector, the higher its specificity.
ul li a {
  color: brown;
}

Selector Combinations:

  • Different types of selectors can be combined to increase specificity.
#unique-id .my-class {
  color: pink;
}

Calculating Specificity

Calculating Specificity:

  • Count the number of:
    • IDs in the selector.
    • Classes, attributes, and pseudo-classes in the selector.
    • Elements in the selector.
  • Write the specificity as a four-digit number (e.g., 0123).
  • The higher the number, the higher the specificity.

Examples

Examples:

/* Specificity: 0010 */
p {
  color: red;
}

/* Specificity: 0100 */
.my-class {
  color: blue;
}

/* Specificity: 1000 */
#unique-id {
  color: green;
}
/* Specificity: 0011 */
div p {
  color: purple;
}

/* Specificity: 0101 */
.container .my-class {
  color: orange;
}

/* Specificity: 1001 */
#unique-id .my-class {
  color: pink;
}

!important

!important:

  • !important declaration has the highest specificity and should be used sparingly.
.important-rule {
  color: gold !important;
}

Understanding specificity is crucial for managing styles and avoiding unexpected results. Use it wisely to create maintainable and predictable stylesheets.