Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Why do we need these attributes selectors?

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

2 Answers

Hello

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.

Example

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

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

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.