Advanced styling with CSS attribute selectors

Advanced styling with CSS attribute selectors cover image

There are many ways to target HTML elements using CSS selectors, we mostly use the three common ones; tag, class and id selectors, but there are a lot more advanced ways to target elements.

We'll be looking at how to target elements by their attributes and values.

To target an element by its attribute, we wrap the attribute name in a pair of square brackets: [], so if we wanted to target all elements having the href attribute;

[href] {
  color: red;
}

Elements affected by that styling would look like these:

<a href="https://google.com">Google.com</a> <a href="https://theninja.blog">The Ninja Blog</a>

How to style elements based on the attribute value

It's also possible to style such elements based on the values of their attributes, the selectors for targeting attribute values are listed below.

The attribute value equals selector [attribute=value]

This selector targets elements whose attribute value match the ones specified. An example snippet:

a[target='_blank'] {
  color: green;
}

Elements targeted look like this:

<a href="https://google.com" target="_blank">Google</a>

So CSS is targeting elements whose target attributes are equal to _blank.

The attribute starts with value selector [attribute^=value]

This selector targets elements whose attribute value starts with the specified word. Example:

p[class^='red'] {
  color: red;
}

Elements styled will look like this:

<p class="red blue orange">This will be a paragraph with red text</p>

The attribute contains certain value selector [attribute*=value]

This selector targets elements whose attribute values contain the specified substring regardless of the position. Example:

p[class*='blue'] {
  color: blue;
}

Elements targeted will look like these:

<p class="red yellowblue orange">This will be a paragraph with blue text</p>
<p class="blueyellow red orange">This will also be a paragraph with blue text</p>

The attribute ends with value selector [attribute$=value]

This selector targets elements whose attribute values end with the word specified in the selector. Example:

p[class$='orange'] {
  color: orange;
}

Elements targeted will look like these:

<p class="red blue orange">This will be a paragraph with orange text</p>

The attribute has value selector [attribute~=value]

This selector targets elements whose attribute contains a specific value separated by space, meaning that it matches the entire word and not a substring.

Example:

p[class~='red'] {
  color: red;
}

Elements targeted look like:

<p class="yellow red blue">This will be a paragraph with red text</p>

These are the most used attribute selectors out there, there are a few more, you can read about the rest on CSS Tricks here.

Found the article helpful?

Subscribe to my Newsletter to receive new articles in your inbox 👇

No spamming, just fresh articles straight out of the oven.