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 How to Make a Website Styling Web Pages and Navigation Style the Image Captions

How specific to be when coding CSS???

Hello,

So, when we styled the image captions, we began the declaration with the code: #gallery li a p......however, when we styled the nav links, we started the code with: nav a. Why wasn't it: nav li a??? Or why wasn't it just #gallery p??? I'm confused.

2 Answers

Very good question. You know what CSS stands for: Cascading Style Sheets. The name basically means that rules will cascade over each other, with some being overridden by later rules or by more specific rules.

One of the rules of this cascade is that specific selectors override more general selectors. That is, a selector like #gallery li a p will override #gallery p because the former is more specific. There are other a few rules too; for instance, ID selectors (#gallery) will override class selectors (.post). Guil discusses a lot of these rules in his CSS Basics course, which you should take soon after you finish this first course.

As a rule of thumb, be as general as you reasonably can. Overly specific selectors are much more likely to break as you make edits to your code further down the road, they're much harder for other developers to understand, and they're also slower for the web browser to render (though this last one is becoming less of a concern with the amazing browsers and hardware we have these days).

Hope this helps! And welcome to Treehouse! :)

EDIT: I said that selectors that got too specific are bad. The opposite is also true; if your selectors are too broad, your styles can leak out of their rules, and that's not fun at all. Fortunately, it's a lot easier to prevent broad selectors than specific ones; just try to scope any tag-name selectors you have (instead of h1, select by #article h1).

Great answer, I wish someone said the same to me when I started out with CSS.

I also have a very long post here on the forums where I talk about keeping CSS and HTML code clean and DRY. If you're interested in finding out more, I suggest you give it a read as well. :)

Thanks, Ryan. That definitely helped.