Attribute Selectors & Combinators
Attribute selectors target elements based on their HTML attributes and values. Combinators define relationships between selectors — child, descendant, sibling. Together they enable precise, context-aware styling.
Attribute Selectors & Combinators
- [attr] — Has the attribute: [disabled] selects all disabled elements
- [attr='value'] — Exact match: [type='email'] selects email inputs
- [attr^='value'] — Starts with: [href^='https'] selects secure links
- [attr$='value'] — Ends with: [href$='.pdf'] selects PDF links
- [attr*='value'] — Contains: [class*='btn'] selects elements with 'btn' in class
- > — Child combinator: div > p selects direct children only
- ~ — General sibling: h2 ~ p selects all <p> after <h2> (same parent)
- + — Adjacent sibling: h2 + p selects only the <p> immediately after <h2>
Attribute Selectors Code
/* Style external links differently */
a[href^="https://"]::after {
content: ' ↗';
font-size: 0.8em;
}
/* PDF links get an icon */
a[href$=".pdf"]::before {
content: '📄 ';
}
/* Style all required inputs */
input[required] {
border-left: 3px solid #E44D26;
}
/* Adjacent sibling: only first p after heading */
h2 + p {
font-size: 1.1em;
color: #555;
/* Lead paragraph styling */
}
/* All siblings after a class */
.divider ~ li {
border-top: 1px solid #eee;
}
/* Data attributes for custom styling */
[data-theme="dark"] { background: #1a1a2e; color: white; }
[data-status="active"] { border-color: #2ecc71; }Tip
Data attributes are a powerful styling hook: [data-status='active'] { border-color: green }. Unlike classes, data attributes carry semantic meaning and can be set dynamically with JavaScript — ideal for state-driven styling.
Selectors target HTML elements for styling
Common Mistake
Overusing [class*='btn'] — it matches any element with 'btn' anywhere in its class, including 'submit-btn-wrapper'. Use actual class selectors (.btn) for intentional styling; attribute selectors only for existing HTML attributes.
Practice Task
Add smart link styling: (1) External links a[href^='https://'] get ↗ icon via ::after, (2) PDF links a[href$='.pdf'] get 📄 icon, (3) Required inputs get left accent border, (4) h2 + p styles lead paragraphs.
Quick Quiz
Key Takeaways
- Attribute selectors target elements based on their HTML attributes and values.
- [attr] — Has the attribute: [disabled] selects all disabled elements
- [attr='value'] — Exact match: [type='email'] selects email inputs
- [attr^='value'] — Starts with: [href^='https'] selects secure links