简体   繁体   中英

SCSS ampersand and multiple parent selectors

I have just converted all of the style of my current project from Less to SCSS and I have a complex SCSS selector made of multiple selectors separated by commas that is now compiled completely differently.

I have background classes for my sections and I want to remove the top padding of a section with the same bg class as the previous one.

.bg{
    &--1, &--2, &--3, &--4,
    &--5, &--6, &--purple,
    &--pink, &--cyan{
        &.section + &.section{
            & > .padd{
                padding-top: 0;
            }
        }
    }
}

I don't have the Less output anymore, but the ampersands in &.section + &.section should be only representing one of the parent selectors(eg .bg--1.section +.bg--1.section ) but it is now representing every possible case (eg .bg--1.section +.bg--1.section, .bg--1.section +.bg--2.section , etc.) which is now applying to every section instead of only on repeated background sections and creating an endless css selector (15,798 characters, holy cow).

I know that the Less ampersand parent selector is not interpreted the same way as SCSS but I need to know how I could achieve the result I had in Less.

I have managed to find an easy fix for this problem.

There is a @each loop in SCSS. Having all the color variables' names in a single list variable for an @each loop gave the exact same results as Less would normally do by default. This is what the SCSS looks like now:

$colors: 1, 2, 3, 4, 5, 6, purple, pink, cyan;

@each $color in $colors {
    &--#{$color}{
        &.section + &.section{
            & > .padd{
                padding-top: 0;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM