CSS course menu
CSS Attribute Selectors: [attr], [attr=value], ^=, $= and *=
Learn CSS attribute selectors with examples: selecting by the presence of an attribute, exact values, values that start with, end with or contain text, words in a list, and case-insensitive matching, with practical uses for links, inputs and data attributes.
On this page
Attribute selectors match elements based on their attributes and attribute values. They are written in square brackets.
Presence and exact value#
/* Any element with a title attribute */
[title] {
border-bottom: 1px dotted;
cursor: help;
}
/* Inputs whose type is exactly "email" */
input[type="email"] {
border: 2px solid #2f5fe0;
}<p>Hover over <abbr title="Cascading Style Sheets">CSS</abbr>.</p>
<p><input type="text" placeholder="Name"> <input type="email" placeholder="Email"></p>Matching part of a value#
a[href^="https://"]::after { content: " ↗"; }
a[href$=".pdf"]::after { content: " (PDF)"; }
a[href^="mailto:"] { color: green; }<p><a href="/about">About us</a> (internal link)</p>
<p><a href="https://developer.mozilla.org">MDN</a> (external link)</p>
<p><a href="/files/fees.pdf">Fee structure</a></p>
<p><a href="mailto:hello@example.com">Email us</a></p>The ::after part adds text after each link; it is a pseudo-element, covered in Pseudo-elements.
Case-insensitive matching#
Add i before the closing bracket to ignore case:
a[href$=".pdf" i] { } /* matches .pdf, .PDF and .Pdf */Styling data attributes#
Attribute selectors pair well with data-* attributes for state:
.order[data-status="shipped"] { color: green; }
.order[data-status="cancelled"] { color: #999; text-decoration: line-through; }<p class="order" data-status="placed">Order 101: placed</p>
<p class="order" data-status="shipped">Order 102: shipped</p>
<p class="order" data-status="cancelled">Order 103: cancelled</p>JavaScript can change the attribute (element.dataset.status = "shipped") and the styles follow automatically.
Accessibility attributes as hooks#
Styling based on ARIA and state attributes keeps the visual state and the accessible state in sync:
button[aria-expanded="true"] { background: #eef3ff; }
a[aria-current="page"] { font-weight: bold; }Practice#
Practice exercise
Make every link to a .zip file show " (ZIP)" after it, make external links (starting with http) italic, and give required inputs (those with the required attribute) a red left border.
Show solution
a[href$=".zip" i]::after { content: " (ZIP)"; }
a[href^="http"] { font-style: italic; }
input[required] { border-left: 4px solid red; }<p><a href="/downloads/project.zip">Starter files</a></p>
<p><a href="https://www.w3.org/">W3C</a></p>
<p><input placeholder="Name (required)" required> <input placeholder="Nickname"></p>Key takeaway#
Finished this lesson?