I have a number of nested elements, and I'm trying to select only the first N levels. The below shows a working example, where I'm selecting the first 7 levels and styling them. That works exactly how I want, however, I was hoping there was a simplified way of selecting these elements.
In my actual use case, I don't know the total number of nested elements, and I'm trying to select the first 50 levels, so using the above method would be quite messy. Unfortunately, I can't change the HTML in my application, so it needs to be a CSS only method. Thanks.
.container > div,
.container > div > div,
.container > div > div > div,
.container > div > div > div > div,
.container > div > div > div > div > div,
.container > div > div > div > div > div > div,
.container > div > div > div > div > div > div > div {
border-left: 1px solid;
padding-left: 15px;
}
<div class="container">
<div>
A
<div>
B
<div>
C
<div>
D
<div>
E
<div>
F
<div>
G
<div>
H
<div>
I
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is impossible in all CSS versions up to present and as far as I know a Descendant Level Selector
that selects all elements up to a specified level is not planned to be implemented anytime soon.
What you can do instead is set a class to all the elements you want to be selected and use:
.container .class {
border-left: 1px solid;
padding-left: 15px;
}
If you can't make any alterations in your HTML or use JavaScript, then what you currently have is your best bet.