Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,729 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!