Ever wondered why a CSS style you wrote is affecting everything — or nothing at all? That’s because CSS selectors need to be sharp and scoped. Let’s explore how to precisely target elements without unexpected results.
📌 1. Selecting a Child Inside a Parent
Suppose your HTML looks like this:
class="card">
class="title">My Blog Post
You want to style .title
only when it’s inside .card
. Use:
.card .title {
font-size: 20px;
}
✅ This applies to .title
at any nesting level inside .card
.
📏 2. Targeting Only Direct Children
If you want styles to apply only when the .title
is directly inside .card
(not nested deeper), use the >
selector:
.card > .title {
font-size: 20px;
}
🚫 This won’t apply if .title
is wrapped like this:
class="card">
class="title">Nested Title
🚫 3. Avoid Class Combinations That Don’t Exist
You might see this and get confused:
.card.featured .title {
color: gold;
}
This selector only works when your HTML is:
class="card featured">
class="title">Golden Post
If you don’t have featured
in your class list, this style simply won’t apply. No errors, no warnings — just silence.
🧼 4. Scoping Styles for Specific Sections
When you want to style something only on a specific page or component, create a unique class:
class="profile-page">
class="card">
class="title">User Info
Then:
.profile-page .card .title {
font-weight: bold;
}
This keeps your styles clean, predictable, and component-friendly.
🧪 5. Bonus: Use :has()
to Style Based on Child Presence (Modern CSS)
If you want to style a parent only if it contains a certain child:
.card:has(.title) {
border: 1px solid green;
}
⚠️ Works in modern browsers like Chrome and Safari. Not supported everywhere yet.
✅ Cheat Sheet Summary
Goal | CSS Selector |
---|---|
Any child inside a parent | .parent .child |
Only direct child | .parent > .child |
Parent with multiple classes | .parent.special |
Scoped styling | .section .child |
Conditional parent styling | .parent:has(.child) |
This is your CSS aiming guide — no more accidental global styles or head-scratching "why isn’t it working?" moments. Use the right selector, and your UI will behave like a dream.