首页 > 解决方案 > Sass – 连接到@at-root 选择器

问题描述

我经常使用@at-root(因为类是动态添加和从正文中删除的),我想知道下面这样的事情是否可行?

header.main {
    @at-root body[class*="contact"] #{&}, body.text-single #{&} {
        background-color: white;
        &.header-is--hidden {
            background-color: red; // I know this won't work
        }
    }
}

而不是必须写:

header.main {
    @at-root body[class*="contact"] #{&}, body.text-single #{&} {
        background-color: white;
    }
    @at-root body[class*="contact"].header-is--hidden #{&}, body.text-single.header-is--hidden #{&} {
        background-color: red;
    }
}

标签: csssass

解决方案


我想知道像下面这样的事情是否可行?

是的

您可以将 header.main 选择器保存在变量中并使用插值将其渲染出来——例如:

header.main {
  $sel: &;  //  contains header.main

  @at-root body[class*="contact"], body.text-single {
    #{$sel} {
      background-color: white;
    }
    &.header-is--hidden #{$sel} {
      background-color: red;
    }
  }
}

CSS 输出

body[class*="contact"] header.main, 
body.text-single header.main {
  background-color: white;
}
body[class*="contact"].header-is--hidden header.main, 
body.text-single.header-is--hidden header.main {
  background-color: red;
}

推荐阅读