DEV Community

Cover image for CSS Attribute Selectors
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

CSS Attribute Selectors

In CSS, there are many ways to styling objects, but there are some great selectors.
Let's find out if you knew about these!

Let me know in the comments how much 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>
Enter fullscreen mode Exit fullscreen mode

We are going to be styling links today, they all have their own characteristics.

CSS [attribute="value"] Selector

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

a[target='_blank'] {
  &:before {
    content: '🆕';
  }
}
Enter fullscreen mode Exit fullscreen mode

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 where the title attribute contains the word Tips

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

CSS [attribute|="value"] Selector

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

We can use it as follows:

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

with the | selector it has to start with a full word or been 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: '🔒';
  }
}
Enter fullscreen mode Exit fullscreen mode

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: '📑';
  }
}
Enter fullscreen mode Exit fullscreen mode

CSS [attribute*="value"] Selector

With the *=value selector we get all attributes that contain a specific value.

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

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

Top comments (0)