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

What Is The Purpose Of Attribute Selectors For Specific Elements?

I can understand why you would use attribute selectors if you wanted to select a group of classes, or many different elements.

But the videos examples of using attribute selectors for specific elements, ex. the submit box. Doesn't make sense, when you could just use an id selector. It seems more complicated and has longer code. Am I missing something here?

2 Answers

Ryno Botha
PLUS
Ryno Botha
Courses Plus Student 4,055 Points

id Selectors can only be used once~

“id” Is Not Equal to #id:

Suppose you have the following HTML:

<div id="box"></div> 

You can target that element via CSS in many ways, and two of those ways directly involve the id element. The obvious way is:

#box{;}

But you can also target the element quite specifically using an attribute selector, like this:

[id="box"] { width: 400px;}

Both methods shown above will target the box just fine. But according to CSS specificity rules, an ID selector has more weight than an attribute selector, so be careful when using the attribute selector in this way, as it’s not as specific as it appears.

To be honest, I think it would be next-to-impossible to have a situation that required that you use the attribute selector to target an element via its ID. But I think it’s good to keep this kind of thing in mind because it reminds us that CSS does have a natural cascade wherein element targeting is decided based on specificity.

Also More about Attribute Selectors:

+You Don’t Have to Specify an Actual HTML Element

+You Can’t Target User Agent Attributes

+IE7 Can’t Target the “style” Attribute

+Value-less Attributes Can Be Tricky Across Browsers

+Case Sensitivity is Tricky Across Browsers

+CSS3 Adds New Attribute Selectors

+Chaining Attribute Selectors (li a[title*='stooge'][title^='the'] {color: red;})

+Styling Similarly Named Attributes

+Handling Multiples Values

+Repeating Attributes

With just a little bit of code, you can achieve remarkably specific targeting with little to no additional markup required.

Great reply, thank you.

Need to wrap my head around that.