如何直接扩展SCSS父选择器?

时间:2019-05-04 11:27:31

标签: css sass extend extending

我有以下代码:

article.featured {
  h4 { margin-bottom: 20px }
  :first-child {
    height: 100%;
    padding-top: 0;
    padding-left: 0;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    .img { @extend &; }
  }
  :last-child {
    padding-top: 0;
    padding-right: 0
  }
}

这是第10行:

.img { @extend &; }

问题是,当我尝试编译此样式表时,出现以下错误:

Parent selectors aren't allowed here.
  ╷
10│     .img { @extend &; }
  │                    ^
  ╵
  stdin 10:20  root stylesheet on line 10 at column 20

如何解决此错误并使用父(.img)元素的属性扩展&元素?

1 个答案:

答案 0 :(得分:0)

我发现将.img选择器移到:first-child选择器旁边并将选择器更改为:first-selector, :first-selector .img时,它可以工作。

这是工作代码(注意:3):

article.featured {
  h4 { margin-bottom: 20px }

  :first-child, :first-child .img {
    height: 100%;
    padding-top: 0;
    padding-left: 0;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }

  :last-child {
    padding-top: 0;
    padding-right: 0
  }
}

编译为:

article.featured h4 {
  margin-bottom: 20px;
}

article.featured :first-child, article.featured :first-child .img {
  height: 100%;
  padding-top: 0;
  padding-left: 0;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

article.featured :last-child {
  padding-top: 0;
  padding-right: 0;
}