【问题标题】:scss prepend selector to current selectorscss 将选择器添加到当前选择器
【发布时间】:2020-02-04 19:38:30
【问题描述】:

有没有办法将选择器直接添加到 scss 中的当前选择器。考虑以下几点:

.object-fit {
  object-fit: cover;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

有没有办法在img 前面加上img.object-fit

我见过的唯一方法是添加&,如下所示:

.object-fit {
  img & {
  }
}

但这会将它变成一个父子选择器:img .object-fit

通常的方法是在第二个选择器后面加上&img,但是因为它在选择器之前没有点,所以最终得到一个不同的类名:.object-fitimg

所以基本上问题是在对象适配类中是否有前置裸元素选择器?

【问题讨论】:

  • 你试过img&吗?
  • @Blazemonger 这是 SCSS 解析器中的语法错误。 Invalid CSS after "img": expected "{", was "&" "&" may only be used at the beginning of a compound selector.
  • 类似@at-root img#{&}?
  • @ReSedano 将其作为答案,它有效。干得好!
  • @ReSedano 非常感谢,添加答案,我会在允许时接受

标签: css sass


【解决方案1】:

如果您使用 @at-root& 与插值语法:

 .object-fit {
      @at-root img#{&} {
        color: blue;
      }
    }

您的输出将是:

img.object-fit{
  color: blue;
}

【讨论】:

  • 为什么是@at-root?这将假设目标始终是退出当前的嵌套选择器。
  • @Trollsyn 如果我不使用@at-root,它会编译为.object-fit img.object-fit
  • @Trollsyn 没问题! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
相关资源
最近更新 更多