سؤال

Today I was looking at some sample code I found and noticed that the developer used a "+" instead of a "," to select two classes.

.region + .region{
    border-left: 1px solid lightgray;
    padding-left: 3.5%;
    margin-left: 4%;
}

What does the "+" sign do that the "," doesn't? Why would you use it? curiously the same class was selected twice here. Why?

Here is a link to the code pen... http://codepen.io/adobe/pen/vKixh

Im just learning CSS3 and any help would be appreciated. Thanks

هل كانت مفيدة؟

المحلول 2

+s and ~s Are Siblings

<div>
    <div class="c"></div>
    <div class="x"></div>
    <div class="y"></div>
</div>

using .c + div {} will style "x" CSS ONLY WORKS DOWNWARDS!

,s Are Multiple Classes

<div>
    <div class="c"></div>
    <div class="x"></div>
</div>

using .c, .x {} will style both "c" and "x" the same way.

No Space Means More Conditions

<div>
    <div class="c x"></div>
    <div class="c"></div>
    <div class="x"></div>
</div>

using .c.x {} will style "c x"

نصائح أخرى

They are NOT the same!

+ is the adjacency selector, e.g. selects .region elements following .region elements.

A comma separated list simply allows you to apply one block of styling to multiple classes, thus:

.region, .region{}

Wouldn't actually perform any action that just .region{} wouldnt by itself.

Adjacency selector (MDN article)

(+) This is referred to as an adjacent selector. It will select only the specified element that immediately follows the former specified element.

This in mind, .region + .region{} would only apply the styling to a .region after another one, and NOT one in isolation, or the first.

This is not an alternative notation to , (comma): the + has a totally different meaning, because it is the immediate sibling selector (or adjacent selector), so your rule matches a .region element only when it's adjacent to another previous .region element.

If you have several sibling .region elements, like this

<div class="region">...</div>
<div class="region">...</div>
<div class="region">...</div>
<div class="region">...</div>

.region + .region will match every .region element except the first one.

Since this a CSS2 selector, an equivalent CSS3 selector would be .region:nth-child(n+1)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top