如何在SASS中使用父选择器将类链接到元素 [英] How to chain a class to an element with a parent selector in SASS

查看:62
本文介绍了如何在SASS中使用父选择器将类链接到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SASS (scss) 执行以下操作.

I'm trying to do the following with SASS (scss).

.class {
  // Base class styles

  a.& {
    // Additions for when applied to a link
  }
}

但我收到一个编译器错误:

But I get a compiler error:

a."后的 CSS 无效:预期的类名,是&"

任何想法如何实现这一目标?目前我刚刚摆脱嵌套,但对我的情况来说这是次优的.

Any ideas how to achieve this? Currently I just break out of nesting, but it's sub optimal for my case.

谢谢!

推荐答案

截至 SASS 3.4,您可以使用@at-root 指令,以便将选择器的范围限定为根目录.

As of SASS 3.4, you can use the @at-root directive in order to scope the selector to the root.

此外,您还需要插入父选择器,&,例如:a#{&}:

In addition, you will also need to interpolate the parent selector, &, like: a#{&}:

.class {
  // Base class styles

  @at-root a#{&} {
    color: #000;
  }
}

将编译为:

a.class {
  color: #000;
}

<小时>

值得一提的是,你可以在@at-root下嵌套多个元素:

.class {
  // Base class styles

  @at-root {
    a#{&} {
      color: #f00;
    }
    p#{&} {
      float: left;
    }
  }
}

将编译为:

a.class {
  color: #f00;
}
p.class {
  float: left;
}

这篇关于如何在SASS中使用父选择器将类链接到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆