CSS Selectors 101: Targeting Elements with Precision
Source: Dev.to
Introduction
CSS selectors are patterns that allow you to choose which HTML elements you want to style. Without them you cannot apply colors, fonts, or layouts to your page.
Element Selector
Targets all elements of a specific type, like all paragraphs:
p {
color: blue;
}
All paragraph text will appear in blue.
Class Selector
Use a . in front of the class name.
.highlight {
color: red;
}
Test
Test
ID Selector
IDs are unique identifiers for a single, specific element. Each ID should appear only once per page.
#header {
font-size: 30px;
}
## Heading
Group Selectors
Group selectors with commas to apply the same style to multiple elements.
h1, h2, h3 {
font-family: arial;
}
Descendant Selectors
Target elements that are inside other elements.
article p {
color: blue;
}
Selector Priority: The Basics
When multiple selectors target the same element, CSS decides which style to apply based on specificity:
ID Selector > Class Selector > Element Selector
What a color?