user6885115
user6885115

Reputation:

SCSS target immediate parent

I have the following scss code that I'm trying to tidy up.

$colors-2: #222;
$colors-1: #ff0;

.footer__region {
  text-align: center;

  &--country {
    color: $colors-2;
    cursor: pointer;
    display: inline-block;

    .heading-3 {
      border-bottom: 2px solid transparent;

      .active & {
        border-bottom-color: $colors-1;
        color: $colors-1;
      }
    }
  }
}

I thought I could nest the .active inside and add the & after to output the following

.footer__region--country.active .heading-3 {
  border-bottom-color: #ff0;
  color: #ff0;
}

But that doesn't seem like I can. Does anyone know of any Sass methods to do this?

Note: .footer__region--country will be the item that has .active attached to it and .heading-3 will be the child.

Upvotes: 0

Views: 502

Answers (1)

Marvin
Marvin

Reputation: 10092

Fortunately, for your example you can make use of the @at-root directive and the fact that .a.b{} selects the same as .b.a{}. This way you do not have to repeat any class name.

$colors-2: #222;
$colors-1: #ff0;

.footer__region {
  text-align: center;

  &--country {
    color: $colors-2;
    cursor: pointer;
    display: inline-block;

    .heading-3 {
      border-bottom: 2px solid transparent;

      @at-root .active#{&} {
        border-bottom-color: $colors-1;
        color: $colors-1;
      }
    }
  }
}

Output:

.footer__region {
  text-align: center;
}
.footer__region--country {
  color: #222;
  cursor: pointer;
  display: inline-block;
}
.footer__region--country .heading-3 {
  border-bottom: 2px solid transparent;
}
.active.footer__region--country .heading-3 {
  border-bottom-color: #ff0;
  color: #ff0;
}

Upvotes: 1

Related Questions