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 CSS Selectors Selectors - Beyond the Basics Child, Adjacent, and General Sibling Combinators

Matthew Keys
Matthew Keys
1,922 Points

Confusion with the ".btn + .btn"

I was just wondering what decides which of the .btn classes gets assigned the 20px to the left margin in the following code:

.btn + .btn {
    margin-left: 20px
}

And I was also wondering what would happen if the following code was used:

.btn + .btn + .btn {
    margin-left: 20px;
}

Thanks in advance

2 Answers

James Matthews
James Matthews
21,610 Points

Hiya Matthew,

the + in CSS is the adjacent sibling selector. It is used to select only the specified element that immediately follows the former specified element within the HTML.

In your example,

.btn + .btn {
     margin-left: 20px;
}

This will set a left-margin of 20px to the second element that has the class '.btn'...but ONLY if they are next to each other in the markup. For example, having this HTML won't work:

HTML:

<p class="btn">Hello</p>
<p class="nothing">Goodbye</p>
<p class="btn">Hello</p>

To answer your other question, having multiple adjacent sibling selectors is perfectly valid, as in your example:

.btn + .btn + .btn {
    margin-left: 20px;
}

This will apply a left-margin to the third element only, assuming the following markup:

<p class="btn">Hello</p>
<p class="btn">Goodbye</p>
<p class="btn">Hello</p> /* this one get's the margin! */

If you did not have another adjacent sibling with that class, the styling would simply do nothing.

Hope this helps!

Matthew Keys
Matthew Keys
1,922 Points

Thank you for the answer. I would just like to ask one more question. What would happen in the following:

HTML:

<p class="btn">Hello</p>
<p class="btn">Goodbye</p>
<p class="btn">Hello</p> 
<p class="btn">Goodbye</p>

CSS:

.btn + .btn + .btn {
  margin-left: 20px;
}
James Matthews
James Matthews
21,610 Points

Hi again Matthew,

That styling will result in the third AND forth p elements getting the left-margin of 20px. Basically, applying the adjacent sibling operator will style ALL elements of that class after it, as long as they are next to each other in the HTML.

:)