CSS attribute selectors target HTML elements based on the presence, exact value, or partial string value of their HTML attributes.
Attribute selectors use square brackets ([...]):
/* 1. Has specific attribute */
input[required] { border: 1px solid #ef4444; }
/* 2. Exact attribute value */
input[type="text"] { background-color: #1e293b; }
/* 3. Starts with prefix (^=) */
a[href^="https://"] { color: #34d399; }
/* 4. Ends with suffix ($=) */
a[href$=".pdf"] { color: #f59e0b; }
/* 5. Contains substring (*=) */
a[href*="github"] { font-weight: bold; }
Selector types explained:
[attr]: Matches elements containing the attribute regardless of value.[attr="val"]: Matches elements with exact attribute value val.[attr^="val"]: Matches values starting with string val.[attr$="val"]: Matches values ending with string val.[attr*="val"]: Matches values containing substring val.flowchart TD
A["Attribute Matchers"] --> B["[href^='https'] -> Starts with 'https'"]
A --> C["[href$='.pdf'] -> Ends with '.pdf'"]
A --> D["[class*='card'] -> Contains substring 'card'"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Attribute Selectors Example</title>
<style>
/* Highlight secure HTTPS links */
a[href^="https://"]::after {
content: " 🔒";
font-size: 0.85em;
}
/* Style file download links */
a[href$=".pdf"] {
color: #f59e0b;
font-weight: bold;
}
/* Target required inputs */
input[required] {
border-left: 3px solid #ef4444;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Attribute Selector Highlights</h2>
<p><a href="https://example.com" style="color: #38bdf8;">Secure Website Link</a></p>
<p><a href="document.pdf">Download PDF Guide</a></p>
</body>
</html>
[href^="https://"] to style external secure links: Automatically appends icons to external links without adding extra classes to HTML markup.[href$=".pdf"] to style download links: Visually indicates file formats for users before they click.[type="..."]: Target specific input fields (input[type="checkbox"]) cleanly.Write a CSS attribute selector targeting links ending in .zip (a[href$=".zip"]) setting color: #f59e0b;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.