使用Sass扩展媒体查询中的选择器

min*_*vor 71 css sass media-queries

我有一个item类和一个紧凑的"修饰符"类:

.item { ... }
.item.compact { /* styles to make .item smaller */ }
Run Code Online (Sandbox Code Playgroud)

这可以.但是,我想添加一个@media查询,.item当屏幕足够小时强制类紧凑.

首先想到的是,这就是我试图做的事情:

.item { ... }
.item.compact { ... }
@media (max-width: 600px) {
  .item { @extend .item.compact; }
}
Run Code Online (Sandbox Code Playgroud)

但是这会产生以下错误:

你可能不会在@media中扩展外部选择器.您只能在同一指令中@extend选择器.

如何使用SASS完成此操作而无需使用复制/粘贴样式?

cim*_*non 85

简单的答案是:你不能因为Sass不能(或不会)为它组成选择器.您不能进入媒体查询并扩展媒体查询之外的内容.如果只是简单地复制它而不是试图组合选择器,那肯定会很好.但事实并非如此.

使用mixin

如果你有一个案例,你将要重新使用媒体查询内外的代码块,并希望它能够扩展它,那么写一个mixin和一个extend类:

@mixin foo {
    // do stuff
}

%foo {
    @include foo;
}

// usage
.foo {
    @extend %foo;
}

@media (min-width: 30em) {
    .bar {
        @include foo;
    }
}
Run Code Online (Sandbox Code Playgroud)

从外部扩展媒体查询中的选择器

这对您的用例不会有所帮助,但它是另一种选择:

%foo {
  @media (min-width: 20em) {
    color: red;
  }
}

@media (min-width: 30em) {
  %bar {
    background: yellow;
  }
}

// usage
.foo {
  @extend %foo;
}

.bar {
  @extend %bar;
}
Run Code Online (Sandbox Code Playgroud)

等到Sass取消这个限制(或自己修补)

关于这个问题有很多正在进行的讨论(请不要对这些线程做出贡献,除非你有一些有意义的东西要添加:维护者已经意识到用户需要这个功能,这只是一个如何实现它的问题以及语法应该是).

  • `%foo` 不需要,`.foo` 可以直接`@include foo`。 (2认同)

min*_*vor 11

为了记录,这里是我最终解决问题的方法,只复制一次生成的样式:

// This is where the actual compact styles live
@mixin compact-mixin { /* ... */ }

// Include the compact mixin for items that are always compact
.item.compact { @include compact-mixin; }

// Here's the tricky part, due to how SASS handles extending
.item { ... }
// The following needs to be declared AFTER .item, else it'll
// be overridden by .item's NORMAL styles.
@media (max-width: 600px) {
  %compact { @include compact-mixin; }

  // Afterwards we can extend and
  // customize different item compact styles
  .item {
    @extend %compact;
    /* Other styles that override %compact */
  }
  // As shown below, we can extend the compact styles as many
  // times as we want without needing to re-extend
  // the compact mixin, thus avoiding generating duplicate css
  .item-alt {
    @extend %compact;
  }
}
Run Code Online (Sandbox Code Playgroud)