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 trialJakub Tyczyński
3,310 PointsQuestion about targeting with class selector
Hi, could someone be so kind and explain me why I have to target nav a.seleted insted of trageting just a class?
I'm really confused by this. I was sure that trageting just a class .selected would target that anchor element. I've checked and it does not.
Second question: Why do I have to type nav a.selected and not nav a .selected? Why cant' be space between a and .selected?
Thanks for feedback!
<nav>
<ul>
<li><a href="index.html" class="selected">Portfolio</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
nav a.selected, nav a:hover {
color: #32673f;
}
3 Answers
Charles Smith
7,575 PointsThe first question - why can't you just target .selected.
Basically, you could, but it wouldn't style a link on that class. Let's say it was designed the way you suggested - targeting just ".selected" would style all states which would produce undesired results or limit your options. Instead, you have to be more specific, thus you target a.selected.
In this case, you are even more specific and target nav a.selected. I think that you could get away with not having "nav" there, but it's not a good idea because then you can't reuse the "selected" class.
As for why you can't have a space - it's just not part of the CSS syntax.
Jakub Tyczyński
3,310 PointsOk, I get it why I couldn't reuse this class without overwriting.
But still I can't understand why targeting only that class won't style a link. It works when a change class to an id and target only that id.
Ryan Drake
12,587 PointsThis is due to the specificity of CSS! IDs have more weighting than classes.
More useful notes about specificity here: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
Jakub Tyczyński
3,310 PointsThank you! Now I get it. I was sure they are equally important.