CSS Attribute Selectors

Attribute selectors target elements based on their attributes and values, providing powerful targeting capabilities.

Attribute Selector Patterns

[attr] selects elements with the attribute.

[attr="value"] matches exact value.

[attr~="value"] matches value in space-separated list.

[attr^="value"] matches values starting with text.

[attr$="value"] matches values ending with text.

[attr*="value"] matches values containing text.

/* Has attribute */
input[required] {
  border: 2px solid red;
}

/* Exact match */
a[href="https://example.com"] {
  color: green;
}

/* Contains word */
[class~="button"] {
  padding: 10px;
}

/* Starts with */
a[href^="https"] {
  color: green;
}

a[href^="http://"] {
  color: orange;
}

/* Ends with */
a[href$=".pdf"]::after {
  content: " (PDF)";
}

img[src$=".svg"] {
  width: 100%;
}

/* Contains substring */
[class*="btn"] {
  cursor: pointer;
}

/* Case-insensitive */
a[href*="example" i] {
  color: blue;
}