How to write a selector that works only when you have a specific parent in scss

Asked 2 years ago, Updated 2 years ago, 89 views

The following style sheets are available:
The characters in .a.b.c.d.e are red, but
Blue only when .a.b.active.c.d.e and b are given active.
However, the description of .a.b and .c.d.e is duplicated.

.a.b{
    .c.d.e{
        color:red;
    }
}

.a.b.active{
    .c.d.e{
        color:blue;
    }
}

What should I do to summarize the designation of the pass in one place as follows:
(In this example, .e is incorrect because it means active.)

.a.b{
    .c.d.e{
        color:red;
        &.active {
           color:blue;
        }
    }
}

I was able to go close by using ampersand and at-root as below, but I don't know where to go.

.a.b{
    $x:&;
    .c.d.e{
        color:red;
        @at-root#{$x}.active&{
            color:blue;
        }
    }
}

/* ↓ After css conversion */
.a.b.c.d.e{
  color:red;
}
.a.b.active.a.b.c.d.e {//← Too bad.a.b.active.c.d.e is ideal.
  color:blue;
}

I checked the sash at the following site.
https://www.sassmeister.com/

css sass

2022-09-30 10:14

2 Answers

Considering where is in parallel and where is the condition, I think the following would be true.

.a.b{
    .c.d.e{
        color:red;
    }
    &.active.c.d.e{
        color:blue;

    }
}


2022-09-30 10:14

I'm using Less, but I tried writing it.

.a.b{
    $x:&;
    $y: '.c.d.e';
    # {$y}{
        color:red;
        @at-root#{$x}.active#{$y}{
            color:blue;
        }
    }
}

When I tried it on the same conversion site, the output was as follows:Please check there as well.
https://www.sassmeister.com/

.a.b.c.d.e{
  color:red;
}
.a.b.active.c.d.e{
  color:blue;
}

The shape above is in line with the results of the questioner, but if you want to use variables in the first place,

$x:'.a.b';
$y: '.c.d.e';

#{$x}#{$y}{
    color:red;
}

#{$x}.active#{$y}{
    color:blue;
}

I think it's still more readable.


2022-09-30 10:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.