Answers to Target first `li` having specific class inside `ul` with css only ( 4 )

  1. 2017-01-02 07:01

    try selector :nth-child() and :first-child

    ul li:first-child {  
    //some css 
    }
    

    and

    ul li:nth-child(4) {
     //some css
    }
    
  2. 2017-01-02 07:01

    You can't select with class as parameter for first-child. Instead use ~ operator to select the reverse. i.e apply styles for rest except first child.

    li.a, li.b{
     color: green; /*your styles for first elemenets*/
    }
    li.a ~ .a { /*differentiate rest of them from first*/
      color: black;
    }
    li.b ~ .b {
      color: black;
    }
    <ul>
      <li class="a">1</li>
      <!-- I want to target this li -->
      <li class="a">2</li>
      <li class="a">3</li>
      <li class="b">4</li>
      <!-- and this li -->
      <li class="b">5</li>
      <li class="b">6</li>
    </ul>

  3. 2017-01-02 07:01

    Generally, you can only target an element, a value of a named attribute in it, or the name of an attribute in the element. So, I would say the answer might be...no? (limited to my own knowledge)

    That being said..

    Would it be possible to insert an empty <li> before each item you want to target?

    If so, you can easily select those items like so:

    ul li {
      color: red
    }
    li:empty {
      display: none
    }
    li:empty + li {
      color: green
    }
    <ul>
      <li></li>
      <li class="a">1</li>  <!-- I want to target this li -->
      <li class="a">2</li>
      <li class="a">3</li>
      <li></li>
      <li class="b">4</li>  <!-- I want to target this li -->
      <li class="b">5</li>
      <li class="b">6</li>
    </ul>

  4. 2017-01-02 08:01

    Use the :first-child pseudo-class and the adjacent sibling selector +.

    .a:first-child, /* Select the first child element */
    .a + .b { /* Select the first element with 'b' class */
      background-color: dodgerblue;
    }
    <ul>
      <li class="a"></li>
      <li class="a"></li>
      <li class="a"></li>
      <li class="b"></li>
      <li class="b"></li>
      <li class="b"></li>
    </ul>

Leave a reply to - Target first `li` having specific class inside `ul` with css only

◀ Go back