Search code examples
csscss-selectorspseudo-class

How to use :not and :first-child pseudo selectors simultaneously


I want to select the first li without class="test" using :not and :first-child pseudoclasses. In this example I try to set color blue to <li>Third</li>:

ul li {
    color:red;
}

ul li:not(.test):first-child {
    color:blue;
}
<ul>
    <li class="test">First</li>
    <li class="test">Second</li>
    <li>Third</li>
    <li>Fourth</li>
</ul>


Solution

  • Why not do the below, which uses a combination of rules to filter the item you need (you can combine rules #1 and #3).

    This has the added advantage of it not mattering what the index is of the first item with the class .test

    ul li { /* <-- select all list items */
      color: red;
    }
    li:not(.test) { /* <-- select all list which arent test */
      color: blue;
    }
    ul li:not(.test) ~ li { /* <-- select all list items which follow an item without test */
      color: red;
    }
    <ul>
      <li class="test">First</li>
      <li class="test">Second</li>
      <li>Third</li>
      <li>Fourth</li>
    </ul>