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

mrx3
mrx3
8,742 Points

practicing my child selector and adjacent sibling selector. I have a few questions. (Codpen Included).

I was just practicing with these two selectors and I'm stumped. First I want to style each p tag with a background of green. I know I could use a descendant selector for instance .main-content p, and that will style each p tag with a background of green. I tried .main-content > p which styled every paragraph with the green background. Now I wanted to use .main-content + p, which is the adjacent sibling selector, and the way I understand it the adjacent sibling selector should select the immediate child...the first p, but it doesn't. The adjacent sibling selector is located on line 172 of my code pen. Can some explain to me why the adjacent sibling selector won't work here? I know I can use p:nth-of-type(), and add 1 inside the parenthesis, and it will style the background green. But, I want to use the adjacent way as practice.

Thank you in advance for any help with this. Codepen http://codepen.io/mike316/pen/ByGwYM

1 Answer

Hugo Paz
Hugo Paz
15,622 Points

Hi there,

The adjacent sibling is not a child, it is a 'brother' if you like. Your code will work if you add an p tag after the .main-content

<div class="main-content">
       <p>This paragraph will not be affected with the .main-content + p rule because its a child of .main-content</p>
</div>
<p>This paragraph will be affected by the rule because it is a sibling of .main-content</p>

If you want to affect the first paragraph you can use the :first-child pseudo class.

div p:first-child {
  background: green;

}
mrx3
mrx3
8,742 Points

My ah-ha moment. Thank you so much Hugo, big props for the explanation...most excellent.