CSS Selector Specificity: A Cheat Sheet

CSS selector specificity determines which styles are applied to elements when there are conflicting style rules.
Specificity is calculated based on the type of selectors used in CSS.

Inline Style

Inline styles are considered the most specific, and will overwrite all other style types.

<h1 style="color: green;">This is an inline style</h1>

ID Selectors

ID Selectors are the most specific external style selectors, and overwrite everything other than Inline Styles.

#unique-id { color: red; }

Class Selectors

Class Selectors are less specific than ID Selectors and are used to define styles for multiple items on a page

.class-name { color: blue; }

Attribute Selectors

Attribute Selectors are used to define styles for html elements with specific attributes, for example, input elements with the type "text".

[type="text"]

Pseudo-Class Selectors

Pseudo-class Selectors are used to apply styles to elements based on their state or position in a document, such as changing the color of a link when the mouse hovers over it.

a:hover { color: red; }

Type Selectors

Type Selectors are used to apply styles to elements of a specific type on a page, such as changing the font size for all paragraph elements on a page.

p { font-size: 16px;}

Universal Selector

The Universal Selector targets every element on the page, regardless of type, class or ID. It's often used to reset default styles or apply styles globally.

* { margin: 0; padding: 0; }