CSS选择最多N个层次的嵌套元素 [英] CSS select nested elements up to N levels deep
问题描述
我有许多嵌套元素,并且我试图仅选择前N个级别.下面显示了一个工作示例,在这里选择前7个级别并设置其样式.正是我想要的方法,但是我希望可以有一种简化的选择这些元素的方法.
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.
在我的实际用例中,我不知道嵌套元素的总数,并且我试图选择前50个级别,因此使用上述方法会很混乱.不幸的是,我无法在应用程序中更改HTML,因此它必须是仅CSS的方法.谢谢.
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>
推荐答案
到目前为止,在所有CSS版本中,根据我所知 后代级别选择器
,这都是不可能的>选择所有达到指定级别的元素的计划很快就不会实现.
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;
}
如果您无法在HTML中进行任何更改或使用JavaScript,那么目前最好的选择就是
If you can't make any alterations in your HTML or use JavaScript, then what you currently have is your best bet.
这篇关于CSS选择最多N个层次的嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!