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

mrx3
mrx3
8,742 Points

Just practicing my nth-child selectors. Codepen included.

I'm going to really start to practicing my nth-child selectors. So I decided to make a simple page. My nth-child selectors I'm using are for the two paragraphs in my .main-section div. My question is, did I set the pseudo classes up correctly in my CSS? Thanks in advance for any replies. Codepen: http://codepen.io/mike316/pen/bpEiA

1 Answer

Hi Mr. X,

Assuming that you wanted the 1st paragraph to be orange and the 2nd to be darkblue then the selectors you have would be one way to do it.

.main-content p:nth-child(2) {
  color: orange;
  font-weight: bold;
}

.main-content p:nth-child(3) {
  color: darkblue;
}

I'm not sure how to answer your question. I suppose the answer depends on what your intentions are.

You have mixed siblings here and :nth-of-type may be more appropriate.

.main-content p:nth-of-type(1) {
  color: orange;
  font-weight: bold;
}

.main-content p:nth-of-type(2) {
  color: darkblue;
}

Your 1st selector .main-content p:nth-child(2) is saying "select the 2nd child if it happens to be a paragraph". If that's your intention then it would be the right selector to use.

.main-content p:nth-of-type(1) is saying "select the 1st paragraph". So if that's more like what you wanted then you should use that instead.

For example, let's suppose you now go and add an image in between the two paragraphs. With nth-child your second paragraph will no longer be darkblue because the img is now the 3rd child and it's not a p element. So that's an unmatched selector now.

With nth-of-type the paragraphs will still be orange and darkblue.

mrx3
mrx3
8,742 Points

Thank you for the explanation. I just wanted to select the paragraphs so, "select the 2nd child if it happens to be a paragraph" is what I wanted to do. You're explanation for using nth-of-type is excellent and, very clear. Thank you so much.