CSS select nested elements up to N levels deep

早过忘川 提交于 2020-08-24 10:24:06

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/38596338/css-select-nested-elements-up-to-n-levels-deep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!