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

If CSS is cascading, then why does paragraph link change colour to grey?

Hi,

I have a question regarding the cascading nature of CSS. I thought that CSS is read top to bottom which also means that stylistic changes can be overridden by those implemented further on in your CSS.

However, if this is the case, then why does the paragraph text change colour to grey when there is a later occurring statement that the colour of all links should be green?

I'm referring to the below code in our css:

 #gallery li a p{
  margin: 0; 
  padding: 5%; 
  font-size: 0.75em; 
  color: #bdc3c7;
}

and

 /* links */
a {
  color: #6ab47b;
}

Thanks for your help!

4 Answers

While css primarily works on the cascading function there is a bit more to it. Specificity is also calculated and overrules the cascading layout. In this case as your are being very specific about controlling that element, the 'a' selector dose not apply to it. Here is more information about specificity.

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

The color #bdc3c7 only applies to the elements li, p and a that are within the element id'ed as #gallery. Any paragraph or anchor (aka link) element that's outside of #gallery will not have that color.

So if you have an anchor element outside of #gallery it will take the color #6ab47b.

I think the problem is caused by specificity, which is an important concept albeit a pretty confusing one. Some selectors are more specific than others, for example

#gallery a { 
  color: red;
} 

// is more specific than just

a {
  color: blue;
}

So even though the second statement may occur after the first, the first can still take precedence. It's an issue I run into all the time. I use Chrome developer tools to see what styles are being applied and what is being overridden.

Also, you can override this using the !important keyword. For example:

a {
  color: blue !important;
}

Check out this article for a good explanation.

Hope this helps!

Thanks everyone - appreciate the answers!