Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 204
Alvarez Avatar asked Oct 22 '22 01:10

Alvarez


2 Answers

Use the sibling selector:

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

This targets all the <div> siblings of .e

jsFiddle here

like image 177
Josh Crozier Avatar answered Oct 27 '22 22:10

Josh Crozier


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/

like image 41
ced-b Avatar answered Oct 27 '22 23:10

ced-b