CSS selectors and specificity reference table

Selectors

Selector's name Example Description
Basic
Universal * Selects all elements
Element p Selects all <p> elements
Attribute [title] Selects all elements with attribute [title]
Class .MyClass Selects all element with class .MyClass
Pseudo class :My.PseudoClass Selects all element with pseudo-class :My.PseudoClass
Pseudo element ::My.PseudoElement Selects all ::My.PseudoElement pseudo-elements
Compound or complex selectors
Chaining combinator h3.section-heading Selects CSS selectors can be chained so that rule sets apply only to elements that match all criteria.
Descendant combinator .box p Matching only the <p> element which is inside an element with a class of .box.
Listing combinator div, p Selects all <div> elements and all <p> elements
Child combinator div p Selects all <p> elements where the parent is a <div> element
Adjacent sibling combinator h2 + p Selects only the single <p> element that immediately follows an <h2> element.
General sibling combinator h2 ~ p Selects all <p> elements that follow an <h2>, immediately or not.

Specificity

CSS selector has its place in the specificity hierarchy.

There are four categories which define the specificity level of a selector:

Selector's Name Example
Inline style h1 <style="color: pink;">
IDs #navbar
Classes, pseudo-classes, attribute selectors .test, :hover, [href]
Elements and pseudo-elements h1, ::before

How to calculate specificity!

Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element.

Note: Inline style gets a specificity value of 1000, and is always given the highest priority!

Note 2: There is one exception to this rule: if you use the !important rule, it will even override inline styles!