CSS Attribute Selectors

β€” 5 minute read


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 permalink

<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>

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

CSS [attribute="value"] Selector permalink

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: 'πŸ†•';

CSS [attribute~="value"] Selector permalink

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: 'πŸ’‘';

CSS [attribute|="value"] Selector permalink

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: 'πŸ‡³πŸ‡±';

with the | selector it has to start with a full word or been broken by a dash -

CSS [attribute^="value"] Selector permalink

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 permalink

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 permalink

With the *=value selector we get all attributes that contain 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! permalink

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