首页 文章

Sass .scss:嵌套和多个类?

提问于
浏览
246

我正在使用Sass(.scss)来完成我当前的项目 .

以下示例:

HTML

<div class="container desc">
    <div class="hello">
        Hello World
    </div>
</div>

SCSS

.container {
    background:red;
    color:white;

    .hello {
        padding-left:50px;
    }
}

这非常有效 .

我可以在使用嵌套样式时处理多个类 .

在上面的示例中,我正在谈论这个:

CSS

.container.desc {
    background:blue;
}

在这种情况下,所有 div.container 通常是 reddiv.container.desc 将是蓝色 .

我如何在Sass中嵌入 container

2 回答

  • 458

    您可以使用parent selector reference & ,它将在编译后由父选择器替换:

    对于你的例子:

    .container {
        background:red;
        &.desc{
           background:blue;
        }
    }
    
    /* compiles to: */
    .container {
        background: red;
    }
    .container.desc {
        background: blue;
    }
    

    & 将完全解析,因此如果您的父选择器本身嵌套,则在替换_1155303之前将解析嵌套 .

    这种表示法最常用于编写pseudo-elements and -classes

    .element{
        &:hover{ ... }
        &:nth-child(1){ ... }
    }
    

    但是,您可以将 & 放置在您喜欢的任何位置*,因此也可以使用以下内容:

    .container {
        background:red;
        #id &{
           background:blue;
        }
    }
    
    /* compiles to: */
    .container {
        background: red;
    }
    #id .container {
        background: blue;
    }
    

    但请注意,这会以某种方式破坏您的嵌套结构,从而可能会增加在样式表中查找特定规则的工作量 .

    *: & 前面不允许有空格以外的其他字符 . 所以你不能直接连接 selector & - #id& 会抛出错误 .

  • 6

    如果是这种情况,我认为您需要使用更好的方法来创建类名或类名约定 . 例如,就像你说的那样,你希望 .container 类根据特定的用法或外观有不同的颜色 . 你可以这样做:

    SCSS

    .container {
      background: red;
    
      &--desc {
        background: blue;
      }
    
      // or you can do a more specific name
      &--blue {
        background: blue;
      }
    
      &--red {
        background: red;
      }
    }
    

    CSS

    .container {
      background: red;
    }
    
    .container--desc {
      background: blue;
    }
    
    .container--blue {
      background: blue;
    }
    
    .container--red {
      background: red;
    }
    

    上面的代码基于类命名约定中的BEM方法 . 您可以查看以下链接:BEM - 块元素修改器方法

相关问题