Attribute Selectors Explained

What Attribute Selectors Do

Attribute selectors match elements based on the presence or value of an HTML attribute, using square brackets. They are especially useful for styling form elements and links without adding extra classes.

Presence and Exact Match

/* Any element that has a title attribute at all */
[title] {
  cursor: help;
}

/* Exact value match */
input[type="checkbox"] {
  width: 18px;
  height: 18px;
}

Partial Value Matching

SyntaxMatches when the attribute value...
[href^="https"]starts with "https"
[href$=".pdf"]ends with ".pdf"
[class*="btn"]contains "btn" anywhere
[lang|="en"]equals "en" or starts with "en-"
[class~="active"]contains "active" as one whole word in a space-separated list

A Practical Example

a[href$=".pdf"] {
  padding-right: 20px;
  background: url("/icons/pdf.svg") no-repeat right center;
}

This automatically adds a small PDF icon to any link ending in .pdf, without needing to add a class to every single link in the content.

Case Sensitivity

Attribute value matching is case-sensitive by default. Adding an i before the closing bracket makes the comparison case-insensitive, which is useful for attributes like file extensions that might be typed in different cases.

a[href$=".PDF" i] {
  color: red;
}
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.