使用Sass的嵌套元素和连接类

时间:2018-05-16 15:49:34

标签: css sass nested

我似乎无法让它发挥作用......我想知道这是不是我想象的那样可行,或者我现在只处于大脑状态...

我有两个html块,类的分布如下:

<div class="my-class">
  <div class="my-class-parent-one">
    <div class="my-class-wrapper">
      <div class="my-class-child"></div>
      <div class="my-class-child"></div>
    </div>
  </div>
<div>

<div class="my-class">
  <div class="my-class-parent-two">
    <div class="my-class-wrapper">
      <div class="my-class-child"></div>
      <div class="my-class-child"></div>
    </div>
  </div>
<div>

我的萨斯......

.my-class {
  &-parent-one &-wrapper &-cell { font-size: 1.15rem; }
  &-parent-two &-wrapper &-cell { font-size: 0.85rem; }
}

这不应该等同于:??

.my-class .my-class-parent-one .my-class-wrapper .my-class-child {}    
.my-class .my-class-parent-two .my-class-wrapper .my-class-child {}

3 个答案:

答案 0 :(得分:3)

你的Sass将被编译为:

.my-class-parent-one .my-class-wrapper .my-class-cell {
  font-size: 1.15rem;
}
.my-class-parent-two .my-class-wrapper .my-class-cell {
  font-size: 0.85rem;
}

请注意,开头不会有.my-class选择器。要添加.my-class,您需要更改Sass:

.my-class {
  & &-parent-one &-wrapper &-cell { font-size: 1.15rem; }
  & &-parent-two &-wrapper &-cell { font-size: 0.85rem; }
}

以下是Sass中&符号的更详细文字:The Sass Ampersand

答案 1 :(得分:2)

当您使用SASS嵌套链接一个&符号时,它将只使用父名称继续下一个类。如果你想在延续之前使用&符号包含.my-class,你需要在之前添加一个独立的&符号:

.my-class {
  & &-parent-one &-wrapper &-cell { font-size: 1.15rem; }
  & &-parent-two &-wrapper &-cell { font-size: 0.85rem; }
}

答案 2 :(得分:2)

你的SASS会像这样编译出来:

.my-class-parent-one .my-class-wrapper .my-class-cell {
  font-size: 1.15rem;
}
.my-class-parent-two .my-class-wrapper .my-class-cell {
  font-size: 0.85rem;
}

http://www.cssportal.com/scss-to-css/