Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Every Second Level In CSS

How would you select every second level in the stack of infinite levels using CSS only?

Sample code:

<div>
    1
    <div>
        2
        <div>
            3
            <div>
                4
                <div>
                    5
                    <div>
                        [...]
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Visual example of the preferred result:

enter image description here

Note: no JavaScript assistance needed; there is no problem when the number of levels is known.

like image 896
Osvaldas Avatar asked Mar 23 '13 16:03

Osvaldas


People also ask

How do I target a second sibling in CSS?

Selecting Only the Next Sibling with Adjacent Sibling Combinator ( + ) The + character used in CSS is a combinator — it combines 2 CSS selectors. It selects the second element, only if it is just after the first element, and both elements are children of the same parent.

How do I select all 3 children in CSS?

Yes, you can use what's known as :nth-child selectors. In this case you would use: li:nth-child(3n) { // Styling for every third element here. }

What are the 3 main ways we can select an item through CSS?

Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)


1 Answers

While there is no problem when the number of levels is known, when it is not known then it becomes impossible with CSS only, not even if you are able to anchor the topmost div to some other element with a selector.

like image 126
BoltClock Avatar answered Oct 04 '22 21:10

BoltClock