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 CSS Foundations Selectors Basic Attribute Selectors

Sharina V. Jones
Sharina V. Jones
11,459 Points

Attribute selector vs descendant selector

This video mentions that using a[class="foo"]{ background-color: crimson; color: white; padding: 5px; }

will allow you to select just the a selector of the foo class. I wanted to find out how this is different from using a descendant selector. Wouldn't typing .foo a { background-color: crimson; color: white; padding: 5px; }

perform the same thing? If so, is there any benefit to using one method over the other?

3 Answers

Andrew McCormick
Andrew McCormick
17,730 Points

attributes are much more selective. when you use [class='footer'] an element that has class="footer grid-1" will not be selected. Only elements that have class="footer" Example: http://codepen.io/anon/pen/EsupC/

Now there are variations on the attribute selectors. See a detailed explanation here: http://css-tricks.com/attribute-selectors/

a[class="foo"] and .foo a do two different things..The first selects links a class of "foo", while the other selects links within a element with a class of .foo.

You'll find attribute selectors sort of handy when working with links that begin with http for example (external links) or ending with .com or maybe styling links that are internal to your site. Other than that you may not use them much.

Mozilla Developers show this in action: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Sharina V. Jones
Sharina V. Jones
11,459 Points

I think the video answered my question. It said the descendant selectors were better because attribute selectors would result in a performance hit. Thanks anyway though!