Why do we need these attributes selectors?

Can't we just put a class on elements and use that?

2 Answers

Liam Clarke
Liam Clarke
Treehouse Moderator 19,804 Points


By these attributes selectors, im assuming you mean attribute CSS selectors, for example: a[title].

That is a good question and many people would argue there is no need when you start to go in to certain CSS methodologies and patterns.

I personally dont use them very often and typically stick to classes following BEM, however there are some use cases where I have in the past.


Lets say your working on a site where you dont have the ability to put classes on HTML, this could be due to it being on a CMS and you have to change all the external links style to display some indicator that you will be leaving this current page, this is typically dont through some external link icon.

You could use attributes to do this with the following:

a[href^="http"] {
  color: green;

/* OR */
a[target="_blank"] {
  color: green;

And this is the HTML that I do not have access to, I cant add any classes due to some restriction. escaping, CMS, etc

    <a href="/blog">Blog</a>
    <a href="/profile">Profile</a>
    <a href="/support">Support</a>
    <a href="https://someexternalresource.com" target="_blank" rel="noopener">Some External Resource</a>

Now all external links are green without adding any classes to the HTML. This is a simplified example but in a real use case, instead of changing the colour to green, you would add styles for an external link icon, one option is using url()

Wow, thank you for the explanation. I can see why someone may need to use them. Could be handy for such reason.