Subscribe

CSS Attribute Selectors

✍️

How many of these CSS Selectors do you know?

20 May, 2020 · 2 min read

There are many ways to style objects in’ CSS’, but there are some great selectors. Let’s find out if you knew about these!

Let me know in the comments how many of them you knew already.

HTML Structure

<div class="container">
  <a href="">Link #1</a>
  <a href="" target="_blank">Link #2</a>
  <a href="" title="Daily Dev Tips">Link #4</a>
  <a href="" lang="nl">Link #5</a>
  <a href="https://daily-dev-tips.com">Link #5</a>
  <a href="http://download.org/file.pdf">Link #6</a>
  <a href="http://google.com/">Link #6</a>
</div>

We are going to be styling links today. They all have their characteristics.

CSS [attribute=“value”] Selector

We can use the attribute=value selector to define a specific attribute with a particular value. The first thing that came to mind was using target="_blank" to identify outgoing links.

a[target='_blank'] {
  &:before {
    content: '🆕';
  }
}

CSS [attribute~=“value”] Selector

The ~ selector is much like the previous one, but it doesn’t have to be a complete hit. It will look for a contained value. In this example, we target every link whose title attribute contains the word Tips.

a[title~='Tips'] {
  &:before {
    content: '💡';
  }
}

CSS [attribute|=“value”] Selector

The |=value selector will get all attributes starting with a specific value.

We can use it as follows:

a[lang|='nl'] {
  &:before {
    content: '🇳🇱';
  }
}

with the | selector, it has to start with an entire word or be broken by a dash -

CSS [attribute^=“value”] Selector

We can also use the ^=value selector to get all attributes starting with a specific value.

a[href^='https'] {
  &:before {
    content: '🔒';
  }
}

CSS [attribute$=“value”] Selector

The $=value selector can be used to get all attributes ending with a specific substring. This is ideal for selector-specific documents.

a[href$='.pdf'] {
  &:before {
    content: '📑';
  }
}

CSS [attribute*=“value”] Selector

With the *=value selector, we get all attributes containing a specific value.

a[href*='google'] {
  &:before {
    content: '🔍';
  }
}

You can see them in action in this Codepen.

See the Pen CSS Attribute Selectors by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Modifying an SVG path with CSS

10 Dec, 2022 · 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 · 2 min read

Animate an SVG path with CSS

Join 2099 devs and subscribe to my newsletter