skip to Main Content

I am sure this is possible but I’m not sure how to achieve it through CSS.

I want to target the 3rd instance of a class the first time the group is found and the 2nd instance the 2nd time it is found.

Here’s an over-simplified example of what I am working with:

<div class="foo">
  <div class="bar">Non Target</div>
  <div class="bar">Non Target</div>
  <div class="bar">TARGET</div>
  <div class="bar">Non Target</div>
</div>
<div class="foo">
  <div class="bar">Non Target</div>
  <div class="bar">TARGET</div>
</div>

Can this be achieved?
N.B. I am trying to achieve this without having to edit the HTML, CSS only

I have tried various combinations of nth-of-type etc but am not experienced enough to figure it out!

3

Answers


  1. Chosen as BEST ANSWER

    I found out how to do it.

    .foo:nth-of-type(1) .bar:nth-of-type(3),
    .foo:nth-of-type(2) .bar:nth-of-type(2) {
      color:yellow;
    }
    

  2. Here is one possible solution. nth-of-type could also be replaced by nth-child, but in both cases it depends whether there are other sibling elements (with no or different classes) on the same level, in which case both wouldn’t work the same way anymore.

    (nth-of-type only works if the element is the nth element of any type inside its parent and has the specified type and class)

    .foo:nth-of-type(1)>.bar:nth-of-type(3) {
      color: red;
    }
    .foo:nth-of-type(2)>.bar:nth-of-type(2) {
      color: red;
    }
    <div class="foo">
      <div class="bar">Non Target</div>
      <div class="bar">Non Target</div>
      <div class="bar">TARGET</div>
      <div class="bar">Non Target</div>
    </div>
    <div class="foo">
      <div class="bar">Non Target</div>
      <div class="bar">TARGET</div>
    </div>
    Login or Signup to reply.
  3. In addition to Johannes solution, we can further target somewhat more accurately using nth-child(n of x) in case there are intervening elements.

    div:nth-child(1 of .foo)> :nth-child(3 of .bar) {
      color: red;
    }
    
    div:nth-child(2 of .foo)> :nth-child(2 of .bar) {
      color: red;
    }
    
    .foo,
    .non {
      margin-bottom: .5em;
      outline: 1px solid grey;
    }
    <div class="foo">
      <div class="bar">Non Target</div>
      <div class="bar">Non Target</div>
      <div class="bar">TARGET</div>
      <div class="bar">Non Target</div>
    </div>
    <div class="non">
      <div class="bar">Non Target</div>
      <div class="bar">Non Target</div>
      <div class="bar">TARGET</div>
      <div class="bar">Non Target</div>
    </div>
    <div class="foo">
      <div class="bar">Non Target</div>
      <div class="not">Non Target</div>
      <div class="bar">TARGET</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search