CSS Selectors – Targeting HTML Elements
Yesterday, I began my CSS journey by learning what CSS is, why it's important, and the different ways to apply it.
Today, I explored one of the most fundamental concepts in CSS: Selectors.
Before CSS can style an element, it needs a way to identify which element should receive the style. That's exactly what selectors do.
Let's dive in.
What is a CSS Selector?
A CSS selector is a pattern used to select one or more HTML elements so that styles can be applied to them.
General syntax:
selector {
property: value;
}
Example:
h1 {
color: blue;
}
Here, the selector is h1, which targets all <h1> elements.
1. Universal Selector (*)
The universal selector targets every element on the page.
* {
margin: 0;
padding: 0;
}
Use Case
It is commonly used to reset browser default spacing.
2. Element Selector
Targets all elements of a specific HTML tag.
p {
color: green;
}
This styles every <p> element.
3. Class Selector (.)
A class selector targets elements that share the same class.
HTML:
<p class="highlight">Hello World</p>
CSS:
.highlight {
background-color: yellow;
}
Multiple elements can share the same class, making it reusable.
4. ID Selector (#)
An ID selector targets a unique element.
HTML:
<h1 id="title">Welcome</h1>
CSS:
#title {
color: red;
}
Unlike classes, an ID should be used only once on a page.
5. Grouping Selector
Apply the same styles to multiple elements.
h1,
h2,
h3 {
color: navy;
}
This reduces code duplication.
6. Descendant Selector
Targets elements inside another element.
div p {
color: purple;
}
Only <p> elements inside a <div> are affected.
7. Child Selector (>)
Targets only the direct children.
div > p {
color: orange;
}
Only immediate child paragraphs are selected.
8. Attribute Selector
Targets elements based on attributes.
input[type="text"] {
border: 2px solid blue;
}
Useful when styling forms.
9. Pseudo-Class Selector
Targets elements in a particular state.
Example:
button:hover {
background-color: black;
color: white;
}
Other common pseudo-classes:
:hover:focus:active:first-child:last-child
These make websites more interactive.
Selector Specificity (Introduction)
Sometimes multiple CSS rules target the same element.
The browser decides which one to apply based on specificity.
General priority:
Inline CSS
↓
ID Selector (#)
↓
Class Selector (.)
↓
Element Selector
↓
Universal Selector (*)
We'll study specificity in more detail later.
Best Practices
✔ Use classes for reusable styles.
✔ Use IDs only for unique elements.
✔ Avoid unnecessary nesting.
✔ Keep selectors simple and readable.
✔ Group selectors when styles are the same.
My Biggest Takeaway
Before today, I thought CSS simply applied styles to HTML elements.
Now I understand that selectors are what make CSS powerful.
They allow us to target exactly the elements we want, whether it's a single heading, a group of buttons, or every paragraph inside a section.
Learning selectors feels like learning how to "communicate" with HTML through CSS.
