SCSS / SASS与&符号的奇怪行为

时间:2016-11-12 04:55:48

标签: sass

我在使用SASS时尝试在父级之后使用Ampersand,以便在父级更改时可以修改元素的行为。

我的scss看起来像这样:

#filter {
    width: 100%;
    height: 68px;
    position: absolute;
    top: 0;
    left: 0;
    transform:translate3d(100%, 0, 0);
    @extend .bg-color--blue;
    @extend .animate;

    &.open {
        transform:translate3d(0, 0, 0);
    }

    .filter {
        width:100%;
        height:100%;

        &__container {
            display:none;
        }

        &__pull {
            width:65px;
            height:50px;
            @extend .bg-color--blue;
            @extend .animate;

            #filter.open & {
                @extend .bg-color--blue-dark;
                color:red;
            }
        }
    }
}

我看到的主线位于层次结构的末尾。 #filter.open & {

目前正在输出:

#filter.open #filter .filter__pull {
    color: red; 
}

我需要输出的是:

#filter.open .filter__pull {
    color: red;
}

我不确定为什么要在那里添加额外的#filter。在我使用它的其他项目中,这没有发生。

任何想法?

3 个答案:

答案 0 :(得分:0)

This is not ideal, but it seems that the Ampersand (&) at the end of the line will copy everything all the way up to the root of your nested SCSS.

I've since removed the class .filter out from under the id #filter (confusing, I know) and made the .filter the base element in the file.

This way, when the & copies the hierarchy, it does not copy all the way up to the #filter element

#filter {
  ...

  &.open {
    ...
  }
}
.filter {
  ...

  &__container {
    ...
  }

  &__pull {
    ...

    #filter.open &  {
      @extend .bg-color--blue-dark;

      i {
        transform: translate3d(-100%, -50%, 0);
        @extend .animate;
      }
    }
  }
}

答案 1 :(得分:0)

#filter {
    width: 100%;
    height: 68px;
    position: absolute;
    top: 0;
    left: 0;
    transform:translate3d(100%, 0, 0);
    @extend .bg-color--blue;
    @extend .animate;

    &.open {
        transform:translate3d(0, 0, 0);
    }

    .filter {
        width:100%;
        height:100%;

        &__container {
            display:none;
        }

        &__pull {
            width:65px;
            height:50px;
            @extend .bg-color--blue;
            @extend .animate;

            @at-root {
                @extend .bg-color--blue-dark;
                color:red;
            }
        }
    }
}

答案 2 :(得分:0)

在这个阶段,我认为您正在努力减少您正在编写的SCSS数量,而不是实际使其更易于可读可管理。为什么不这样做:

#filter {
    ...

    &.open {
        transform:translate3d(0, 0, 0);
        .filter {
            &__pull {
                @extend .bg-color--blue-dark;
                color:red;
            }
        }
    }

    .filter {
        ...

        &__pull {
            width:65px;
            height:50px;
            @extend .bg-color--blue;
            @extend .animate;
        }
    }
}

这更具可读性,您将所有open css分组到自己的块中,因此如果您想要更改类open的值,例如。到active或其他什么,你可以在一个地方改变它。

相关问题