CSS Attribute Selectors

— 5 minute read

permalink

In CSS, there are many ways to style 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>
</div>

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 particular value. The first thing 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 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 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 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! permalink

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