skip to Main Content

I have a simple html hierarchy:

<div>
    <div>
       <div class="custom-class">whatever</div>
   </div>
    <div>
       <div class="custom-class">whatever</div>
   </div>
   <div>
       <div class="custom-class">thing i want to select</div>
   </div>
</div>

I am currently adding attributes to .custom-class but would like to add a specific attribute to only the last-child’s .custom-class.

However I would like to apply the style inside the .custom-class that is being used for all children. Its parent does not have a custom class, nor does the grandparent.

A pseudo example would be:

.custom-class {
    color: red;

    &.where-parent-is-last-child {
        color: green;
    }
}

Meaning, I would like to know the scss selector that can access <div class="custom-class">thing I want to select</div> without affecting the other siblings INSIDE the singular .custom-class class.

2

Answers


  1. :last-child > .custom-class should do what you are asking for: This selects custom-class if it is a direct child of an element that is a last-child.

    :last-child > .custom-class {
      color: green;
    }
    <div>
      <div>
        <div class="custom-class">whatever</div>
      </div>
      <div>
        <div class="custom-class">whatever</div>
      </div>
      <div>
        <div class="custom-class">thing i want to select</div>
      </div>
    </div>
    Login or Signup to reply.
  2. This applies the green color to .custom-class only when it’s the child of a <div> that is the :last-child in its container.

    .custom-class {
      div:last-child > & {
          color: green;
      }
    }
    

    Result

    Here is the compiled CSS with the accompanying HTML in a snippet:

    div:last-child > .custom-class {
      color: green;
    }
    <div>
      <div>
        <div class="custom-class">Whatever</div>
      </div>
      <div>
        <div class="custom-class">Whatever</div>
      </div>
      <div>
        <div class="custom-class">Thing I want to select</div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search