skip to Main Content

I want to do in SCSS something quite simple in vanilla CSS: targeting an element that has two classes.

A simplified example is below:

<div class="parent">
  <div class="child"></div>
  <div class="child child--red"></div>
  <div class="child child--green"></div>
  <div class="child child--red child--green"></div>
</div>

I want to target the child that has both child–green and child–red. I tried stuff like below, but it doesn’t work:

.parent {
  & > .child {
    &--red {
      color: red;
    }
    &--green {
      color: green;
    }
    &--red.&--green {
      color: yellow;
    }
  }
}

I understand why that syntax doesn’t work, considering how the parent selector works, but I’m wondering if there’s an elegant way to do it with the parent selector without having to repeat the child like:

.parent {
  & > .child {
    &--red {
      color: red;
    }
    &--green {
      color: green;
      &.child--red{
        color: yellow;
      }
    }
    // OR
    &--red.child--green {
      color: yellow;
    }
  }
}

Any idea? Thanks!

2

Answers


  1. To target an element with both child–red and child–green classes in SCSS, you can use nested selectors like this

    • ‘>’.child selects .child elements that are direct children of .parent.
    • &–red and &–green apply styles to .child–red and .child–green, respectively.
    • &.child–red.child–green targets .child elements with both classes, applying the combined styles.
    .parent {
      > .child {
        &--red {
          color: red;
        }
        &--green {
          color: green;
        }
        &.child--red.child--green {
          color: yellow;
        }
      }
    }
    
    Login or Signup to reply.
  2. If you want to maintain that syntax, there are two options (the first is not ideal performance-wise, would probably make sense to just write it out as suggested in the other answer)

    Option 1 – Using the :is selector allows you to use both on one line:

    &--red:is(&--green){
      color: yellow;
    }
    

    Option 2 – A bit less fluid and not the best to look at, but you can store the name in a variable and reference it this way so that it’s still managed in one place:

    .parent {
      $childClass: child;
      & > .#{$childClass} {
        &--red {
          color: red;
        }
        &--green {
          color: green;
        }
        &--red.#{$childClass}--green {
          color: yellow;
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search