4

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>
Steve J
  • 43
  • 1
  • 3
  • did you want that each div inside the `container` to be targeted? – geeksal Jul 26 '16 at 17:30
  • *I can't change the HTML in my application, so it needs to be a CSS only method* - It can't be a script either? – BSMP Jul 26 '16 at 17:54
  • Ok, no html changes, but not even jquery? Only with css it is not possible. Please see this topics http://stackoverflow.com/questions/12206935/is-there-a-css-haschildren-selector , http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector?noredirect=1&lq=1 , http://stackoverflow.com/questions/36613187/how-to-select-div-without-descendent-li-in-css?noredirect=1&lq=1 – Madalina Taina Jul 26 '16 at 18:29
  • You can write `.container div` this will select all divs inside container no metter how deep they are – Freestyle09 Feb 24 '21 at 09:30

1 Answers1

2

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.

Angel Politis
  • 9,949
  • 12
  • 43
  • 62