How Do CSS Attribute Selectors Target HTML Elements?

CSS attribute selectors allow developers to target HTML elements based on the presence, exact match, or pattern match of their attributes and values. By matching elements through attributes such as href, type, data-*, or target, these selectors provide granular styling control without requiring dedicated classes or IDs for every element.

Basic Attribute Presence and Exact Match

The most straightforward way to use attribute selectors is by checking whether an attribute exists on an element or whether it matches a specific value exactly.

/* Targets any text input with a disabled attribute */
input[disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}
/* Targets only submit buttons */
input[type="submit"] {
  background-color: #0070f3;
  color: #ffffff;
}

Substring and Pattern Matching Selectors

CSS offers several specialized operators to match parts of attribute values, making it easier to handle dynamic links, file formats, and complex data structures.

/* Targets all secure HTTPS links */
a[href^="https://"] {
  font-weight: bold;
}
/* Targets links pointing to PDF files */
a[href$=".pdf"] {
  padding-right: 20px;
  background: url('pdf-icon.svg') no-repeat right center;
}
/* Targets links containing the word 'blog' in their URL */
a[href*="blog"] {
  color: #d946ef;
}

List and Hyphen Matching Selectors

Certain HTML attributes store whitespace-separated lists or hyphen-separated language codes. CSS provides dedicated operators to handle these formats cleanly.

/* Targets elements with a data-category containing the standalone word 'featured' */
article[data-category~="featured"] {
  border: 2px solid #f59e0b;
}
/* Targets elements with lang="en", lang="en-US", lang="en-GB", etc. */
p[lang|="en"] {
  quotes: "“" "”";
}

Case Sensitivity Modifiers

By default, attribute values in CSS selectors follow the case sensitivity rules of the underlying document language. To ensure consistent matching across different use cases, modern CSS supports explicit case modifiers.

/* Matches .jpg, .JPG, .Jpg, etc. */
a[href$=".jpg" i] {
  border-bottom: 1px dotted #6b7280;
}
/* Matches only the exact casing 'primary' */
button[data-variant="primary" s] {
  background-color: #10b981;
}