Advanced CSS Selectors
Advanced selectors give you more control when targeting elements. These include combinators, attribute selectors, pseudo-classes, and pseudo-elements.
1. Attribute Selectors
Select elements based on the presence or value of attributes.
input[type="text"] {
border: 1px solid #ccc;
padding: 5px;
}
This rule targets all text input fields.
2. Pseudo-classes
Pseudo-classes target elements based on their state or position.
a:hover {
color: red;
text-decoration: underline;
}
li:first-child {
font-weight: bold;
}
Use pseudo-classes for interactivity and advanced targeting without JavaScript.
3. Pseudo-elements
Target specific parts of an element, like the first line or add content before/after.
p::first-line {
font-weight: bold;
}
p::before {
content: "🔹 ";
color: #1d4ed8;
}
4. Combinators
Combine multiple selectors to define relationships between elements.
div p
— Descendant selector (any<p>
inside<div>
)div > p
— Child selector (direct<p>
children only)div + p
— Adjacent sibling (immediately following<p>
)div ~ p
— General sibling (any<p>
after a<div>
)
5. Negation Pseudo-class
Use :not()
to exclude elements from a rule.
p:not(.highlight) {
color: gray;
}
Conclusion
Advanced selectors give you fine-grained control over your styling. Mastering these will allow you to write cleaner and more powerful CSS without relying heavily on JavaScript or excessive class usage.