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 ๐Ÿ“–

Bringing perspective to CSS

7 Aug, 2022 ยท 2 min read

Bringing perspective to CSS

Creating a 3D Cylinder shape in CSS

29 Jul, 2022 ยท 3 min read

Creating a 3D Cylinder shape in CSS

Join 1829 devs and subscribe to my newsletter