1. Inline Styles: Inline styles have the highest specificity and override all other styles.
<div style="color: red;"></div>
  1. ID Selectors: Selectors using IDs have a higher specificity than class and element selectors.
#myDiv {
    color: blue;
}
  1. Class Selectors and Pseudo-classes: Class selectors and pseudo-classes have lower specificity than ID selectors but higher than element selectors.
.myClass {
    color: green;
}

a:hover {
    color: orange;
}
  1. Element Selectors: Element selectors have the lowest specificity.
p {
    color: black;
}
  1. !important: Using !important gives a style the highest specificity, but it should be avoided as it makes styles less predictable and harder to maintain.
p {
    color: gray !important;
}

If selectors have the same specificity, the order in which they appear in the CSS file (or within a <style> block) matters. If two rules have the same specificity, the browser applies the last declaration.

Selector Type Example Code Specificity
Inline Styles <div style="color: red;"></div> 1000
ID Selectors #myDiv { color: blue; } 100
Class Selectors .myClass { color: green; } 10
Element Selectors p { color: black; } 1
Attribute Selectors [type="submit"] { background-color: blue; } 10
Pseudo-classes a:hover { color: orange; } 10
Pseudo-elements p::first-line { font-weight: bold; } 100
Universal Selector * { margin: 0; padding: 0; } 0
Combinators h1 + p { font-style: italic; } 0
Negation Pseudo-class p:not(.special) { color: gray; } 10
Adjacent sibling combinator h2 ~ p { margin-top: 20px; } 0
General sibling combinator h2 ~ p { margin-top: 20px; } 0