Search code examples
csscss-selectorssiblings

Is there a way to STOP selecting after reaching a certain element (using sibling selector)


I am using a sibling selector to select all divs after a certain element. Can I stop selecting after reaching a certain div?


Solution

  • You can use the CSS :not

    In this simple snippet the div after which things are not to be selected is identified by a class, but you can use any means you have of identifying it (e.g. nth-child).

    .parent>div {
      width: 100px;
      height: 100px;
      margin: 10px;
      background: red;
    }
    
    .parent>div:not(.dontselectanythingafterme ~ div) {
      background: lime;
    }
    <div class="parent">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div class="dontselectanythingafterme">dont select anything after me</div>
    
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    
    </div>