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 trialMatthew Keys
1,922 PointsConfusion 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
21,610 PointsHiya 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!
James Matthews
21,610 PointsHi 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.
:)
Matthew Keys
1,922 PointsThanks :)
Matthew Keys
1,922 PointsMatthew Keys
1,922 PointsThank you for the answer. I would just like to ask one more question. What would happen in the following:
HTML:
CSS: