CSS Attribute Selectors

By

Learn how to use CSS attribute selectors to target elements by attribute, from presence checks like p[id] to partial matches with the *=, ^= and $= operators.

~~~

In this post I’ll introduce attribute selectors.

Also see an introduction to the basic CSS Selectors. In there I introduce several of the basic CSS selectors: using type selectors, class, id, how to combine them, how to target multiple classes, how to style several selectors in the same rule, how to follow the page hierarchy with child and direct child selectors, and adjacent siblings.

Attribute presence selectors

The first selector type is the attribute presence selector.

We can check if an element has an attribute using the [] syntax. p[id] will select all p tags in the page that have an id attribute, regardless of its value:

p[id] {
  /* ... */
}

Exact attribute value selectors

Inside the brackets you can check the attribute value using =, and the CSS will be applied only if the attribute matches the exact value specified:

p[id="my-id"] {
  /* ... */
}

Match an attribute value portion

While = lets us check for an exact value, we have other operators for partial matches.

*= checks if the attribute contains a substring. Here every link whose href mentions flaviocopes:

a[href*="flaviocopes"] {
  color: orange;
}

^= checks if the attribute starts with a value. For example, to style every link that points to an https:// URL:

a[href^="https"] {
  /* links to https:// URLs */
}

$= checks if the attribute ends with a value. Style PDF downloads:

a[href$=".pdf"] {
  font-weight: bold;
}

|= matches the value itself, or the value followed by a dash. Common with language codes:

html[lang|="en"] {
  /* matches lang="en" and lang="en-US" */
}

~= matches a whole word in a space-separated list. Handy when an attribute holds several tokens:

div[data-tags~="css"] {
  /* matches data-tags="html css js" */
}

All of these checks are case sensitive by default.

If you add an i just before the closing bracket, the check becomes case insensitive:

a[href$=".PDF" i] {
  /* matches .pdf, .PDF, .Pdf */
}

The i flag works in every current browser. It landed in Chrome 49, Firefox 47 and Safari 9, so you can use it without a fallback.

You can try these selectors on your own HTML with the CSS selector tester.

Tagged: CSS · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about css: