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 trialmrx3
8,742 PointsJust 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
Jason Anello
Courses Plus Student 94,610 PointsHi 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
8,742 Pointsmrx3
8,742 PointsThank 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.