CSS Selectors & Specificity
Understanding how CSS selectors target elements and how specificity determines which styles take priority when multiple rules apply.
Originally written by Carl Mills · January 2018
What Are Selectors?
CSS selectors indicate which HTML elements a style rule applies to. Each rule consists of a selector followed by one or more declarations enclosed in braces.
p {
font-family: Arial;
}
Here, p is the selector, meaning all <p> elements will use the Arial font -
unless overridden by more specific rules.
The Universal Selector
The universal selector (*) targets all elements on the page. It's often used for CSS resets to
remove browser defaults for margin and padding.
* {
margin: 0;
padding: 0;
}
It has the lowest specificity, so any rule defined later for a specific element, class, or ID will override it.
Type and Grouped Selectors
You can target multiple elements at once by separating selectors with commas. These are called type selectors since they refer to HTML tags directly.
p, h1, h3 {
color: red;
}
All paragraphs, H1s, and H3s will be red - unless a more specific selector overrides them.
Class and ID Selectors
Class Selectors
Used to style multiple elements that share the same class name. Defined in CSS using a period
(.).
<p class="myClass">text</p>
.myClass {
color: blue;
}
ID Selectors
Used for unique elements. Defined in CSS using a hash (#).
<p class="myClass" id="myID">text</p>
#myID {
color: green;
}
The ID selector overrides the class selector. In this case, the text will appear green, not blue.
Inline Styles and !important
Inline styles, written directly in HTML, have the highest specificity and will override class and ID styles.
<p style="color: yellow;">text</p>
You can also use !important to force a style, but this is considered bad practice since it breaks
the natural cascading order.
li {
height: 50px !important;
}
Specificity Hierarchy
CSS determines which rule applies by assigning weights to different selectors. The general hierarchy is:
- Inline styles - highest priority
- ID selectors - next highest
- Class selectors - medium priority
- Type/universal selectors - lowest priority
Tools like cssspecificity.com help visualise this hierarchy for complex stylesheets.
Next in the Series
In the next post, we'll look at CSS methodologies - including ITCSS (Inverted Triangle CSS) - and how structured approaches improve scalability and maintainability in larger projects.
Continue to ITCSS Overview →