CSS Selectors 101: Targeting Elements with Precision
Why CSS Selectors Are Needed
CSS selectors let you choose which HTML elements to style. Without selectors, you couldn’t tell the browser which elements should get specific colors, fonts, or layouts. They act like addresses that point to elements in your HTML so styles can be applied where you want them.
Think of selectors like addressing people in a room:
Everyone wearing a red shirt gets style A
Only the person named Alex gets style B
All paragraphs inside a section get style C
Basic CSS Selectors
1. Element Selector
Targets all instances of a specific HTML tag.
p {
color: blue;
}
This selects every <p> on the page.
2. Class Selector
Targets elements with a specific class.
.button {
background-color: green;
}
The dot (.) before a name selects any element with that class. You can reuse it on many elements.
3. ID Selector
Targets a single specific element that has an ID.
#main-header {
font-size: 32px;
}
The hash (#) selects the element with that ID — IDs should be unique in a page.
Group and Descendant Selectors
Group Selectors
Apply the same style to multiple selectors separated by commas.
h1, h2, p {
color: purple;
}
This applies purple text to all matching elements.
Descendant Selectors
Select elements that are inside another element — at any depth.
div p {
color: red;
}
Every <p> that’s inside a <div> gets red text.
This is like saying “apply this style to all paragraphs inside a container.”
Very Basic Selector Priority (High Level)
When more than one rule could apply to the same element, CSS uses specificity to decide which one wins:
Element selectors (lowest priority)
Class selectors
ID selectors (higher priority)
Inline styles (highest)
For example:
p { color: red; }
.text { color: green; }
#main { color: blue; }
If a paragraph has both class text and ID main, the blue rule wins because ID selectors have greater specificity than class or element selectors.
Tips for Beginners
Think of selectors as ways to point to elements in your HTML.
Start simple: element → class → ID.
Group selectors help keep styles DRY (Don’t Repeat Yourself).
Descendant selectors let you style based on HTML structure.
Selectors are the foundation of CSS — mastering them helps you style pages with precision.



