Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS How do I select these elements with css?

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #154738
    noahgelman
    Participant
    <ul>
      <li class="apple"></li>
      <li class="banana"></li>
      <li class="banana"></li>
      <li class="banana"></li>
      <li class="apple"></li>
      <li class="banana"></li>
      <li class="banana"></li>
      <li class="banana"></li>
    </ul>
    

    I want to select the first banana after every apple but I can’t seem to do it.

    I’ve tried using ul li.banana:nth-of-type(3n+1) to select it but for some reason it keeps counting the apple li elements and it’s throwing it off.

    I also can’t use ul li.banana:nth-of-type(4n+2) since this needs to work for cases without apples in it.

    note: I can’t use the “~” selector. I need to stay within the “nth” rules.

    #154740
    Senff
    Participant

    Unless the markup is always the same, you can’t do that with the rules you’ve set. You’ll probably going to have to use JS/jQuery.

    #154741
    Paulie_D
    Member

    Indeed, nth-child & nth-of-type etc. pseudo-classes only work on elements…not classes.

    #154742
    noahgelman
    Participant

    @Senff I’m hoping thats not the case. This takes like 2 seconds to target with jQuery. I’m not sure why CSS has to make things so difficult, lol

    #154744
    Paulie_D
    Member

    I’m not sure why CSS has to make things so difficult, lol

    I’m sure nth-of-class is a major requirement for many but I seem to recall that the working group mentioned that there were major issues with inheritance and specificity in implementing it.

    Much like the long sought ‘parent’ selector.

    In the end…that’s why JQ is such a boon and widely used.

    #154745
    noahgelman
    Participant

    @Paulie_D

    Oh wow. I never knew you couldn’t combine nth-child & nth-of-type with a class selector. That’s the cause of the issue then. I was trying to figure out why it wasn’t working. It’s just ignoring the banana class and just selecting all list items.

    This isn’t doable with the rules in place.

    Thanks a lot for the help guys.

    #154749
    Paulie_D
    Member

    Actually based on this specific requirement

    I want to select the first banana after every apple

    You can do this will CSS..

    .apple + .banana {
      background:red;
    }    
    

    http://codepen.io/Paulie-D/pen/6fae0e9204a8bad638a83df24873b44c

    Sometimes we overlook the obvious options… :)

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘CSS’ is closed to new topics and replies.