Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take in account children for :nth-child

I have some simple html

<div>row1</div>
<div>row2</div>
<div>row3</div>
<div>
    <div>row4.1</div>
    <div>
        <div>row4.2.1</div>
        <div>row4.2.2</div>
    </div>
    <div>row4.3</div>
    <div>row4.4</div>
</div>
<div>row5</div>

and css file

div:nth-child(even)
{
   background-color:green;    
}

I want to make all odd rows green and to not take care of hierarchy. But in result I have this

enter image description here

What am I doing wrong? how to make green rows 2, 4.1, 4.2.2 and 4.4. All other shoud be white.

Is it possible without javascript by css only?

like image 537
Vitalii Avatar asked Oct 01 '22 03:10

Vitalii


1 Answers

Basically, no it is not possible. CSS doesn't work by counting the elements in the document. It treats the document as a tree and you can't treat it any other way.

Your options are to remove the nesting (which ruins the semantics), to style the individual elements (with a class, say, perhaps dynamically generated) or to use Javascript.

One other thing you could do to make it make sense is to add this:

div {
    background-color: white;
}

This is better but still not quite what you want.

like image 199
lonesomeday Avatar answered Nov 15 '22 07:11

lonesomeday