Attribute selector

Attribute selectors allow you to style elements based on their attributes, such as their id, class, type, or custom attributes. This provides more granular control over your styling.

Syntax

element[attribute] {
  /* styles */
}

Breakdown

  • element: The HTML element you want to target.
  • [attribute]: The square brackets indicate an attribute selector.
  • attribute: The name of the attribute you want to match.

Example

<a href="https://example.com">Example Link</a>
a[href^="https://"] {
  color: blue;
  text-decoration: none;
}

In this example, we’re targeting all <a> elements with an href attribute that starts with “https://”.

Common Attribute Selectors

  • Exact Match
a[href="https://example.com"] {
  /* styles */
}
  • Contains a Specific Value
input[type="text"][value="Search"] {
  /* styles */
}
  • Starts with a Specific Value
a[href^="https://"] {
  /* styles */
}
  • Ends with a Specific Value
img[src$=".png"] {
  /* styles */
}
  • Contains a Specific Value
input[type*="text"] {
  /* styles */
}

Combining Attribute Selectors with Other Selectors

You can combine attribute selectors with other CSS selectors to create more complex style rules.

p[class*="error"] {
  color: red;
  font-weight: bold;
}

This rule targets all <p> elements that have a class attribute containing the word “error”.