Introduction
CSS selectors allow you to target HTML elements efficiently. While basic selectors (class, ID, tag) are common, advanced selectors help achieve precision and flexibility in styling.
1. Attribute Selectors
Attribute selectors target elements based on attributes and values.
Basic Attribute Selector
a[target] {
color: red;
}
CSSTargets all <a>
elements with a target
attribute.
Attribute Value Selector
a[href="https://phpdev.in"] {
font-weight: bold;
}
CSSTargets links pointing to https://phpdev.in
.
Partial Match Selectors
input[type^="text"] {
background-color: lightgray;
}
CSS^=
: Starts with$=
: Ends with*=
: Contains
2. Structural Pseudo-Classes
These selectors target elements based on position in the document tree.
:first-child
& :last-child
p:first-child {
color: blue;
}
p:last-child {
color: green;
}
CSSTargets the first and last <p>
in a parent container.
:nth-child(n)
li:nth-child(odd) {
background: lightblue;
}
CSSStyles odd-numbered list items.
:nth-of-type(n)
div:nth-of-type(2) {
font-size: 20px;
}
CSSTargets the second <div>
element among siblings.
3. UI Pseudo-Classes
These selectors respond to user interactions.
:focus
input:focus {
border-color: orange;
}
CSSApplies styles when an input field is focused.
:disabled
button:disabled {
opacity: 0.5;
}
CSSStyles disabled buttons.
Conclusion
Advanced CSS selectors provide powerful ways to target elements dynamically, improving efficiency and reducing reliance on extra classes or JavaScript.