Alvarez
Alvarez

Reputation: 1333

Sibling selector in css

I need to apply css to siblings elements

Example

<div>
    <div class="e"></div>
    <div class="f"></div>
</div>

I want them E and F to be red color, but only if they are siblings.

In case like

<div>
    <div class="e"></div>
</div>
<div>
    <div class="f"></div>
</div>

they are not siblings, so they will have different colors.

No js.

Upvotes: 5

Views: 358

Answers (5)

Samrat
Samrat

Reputation: 387

Hope this works for you.

Demo: http://jsfiddle.net/creativevilla/ae2nf/

HTML:

<div>
    <div class="e">e</div>
    <div class="f">f</div>
</div>

<div>
    <div class="e">e</div>
</div>
<div>
    <div class="f">f</div>
</div>

CSS:

div > div {
 background-color: cyan;   
}

div > div:only-child {  
   background-color: transparent;
}  

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You should manage defining class like this:

html

<div class="sib">
    <div class="e"></div>
    <div class="f"></div>
</div>

<div class="si">
    <div class="e"></div>
</div>
<div class="si">
    <div class="f"></div>
</div>

css:

.sib > e, .sib > f{
     /*code in here */
}

In case your html its easier like this .sib > div{/*code in here */}

And for the second html you can do as this

div.si ~ .e, div.si ~ .f

Upvotes: 0

ced-b
ced-b

Reputation: 4065

Well, this one is a bit crazy, but works as long as you only have two:

.f:nth-child(2), .e:nth-last-child(2) {
   background-color: #ff0000;
}

See fiddle: http://jsfiddle.net/wvLaB/

Upvotes: 1

Sebastian Schmid
Sebastian Schmid

Reputation: 669

not possible.

For some information what is possible, check http://css-tricks.com/child-and-sibling-selectors/.

unfortunately, the ~-operator has a "direction". .e ~ .f would match, but not .f ~ .e.

.e ~ .f means: an ".f", that has an ".e" immediately before, not as a sibling in the common sense!

.e ~ .f selects only class "f", similar to how .ul > .liselects only .li's but not the .ul's. And you can't reverse direction.

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240868

Use the sibling selector:

.e ~ div {
    background-color:red;
}

This targets all the <div> siblings of .e

jsFiddle here

Upvotes: 1

Related Questions