在 Stylus 中对媒体查询进行分组

Grouping Media Queries in Stylus

使用预处理器处理媒体查询非常酷,但我没有找到一种方法来对相同的规则进行分组以避免重复的媒体查询规则,例如:

示例 1

@media only screen and (max-width: 600px) {
  body {
    background-color: #f00;
  }
}
@media only screen and (max-width: 600px) {
  .div1 {
    background-color: #0c0;
  }
}
@media only screen and (max-width: 600px) {
  .div2 {
    background-color: #00c;
  }
}

我想将 相同的规则组合成一个,例如:

示例 2

@media only screen and (max-width: 600px) {
  body {
    background-color: #f00;
  }
  .div1 {
    background-color: #0c0;
  }
  .div2 {
    background-color: #00c;
  }
}

我的触控笔代码

这就是我在 Stylus 中处理媒体查询的方式:

media_queries = {
  mobile  : "only screen and (max-width: 600px)",
  tablet  : "only screen and (min-width: 601px) and (max-width: 800px)",
  desktop : "only screen and (min-width: 801px)"
}

我有一个调用媒体尺寸的函数:

for_breakpoint(breakpoints)
  conditions = ()
  for breakpoint in breakpoints
    push(conditions, media_queries[breakpoint])
  conditions = join(", ", conditions)
  @media conditions
    {block}

之后我在规则里面调用它我想要一个特定的媒体查询:

+for_breakpoint(mobile)
  .div1
    background-color red

但问题是我最终有大量重复的媒体查询,例如 示例 1 中的那些。有没有办法像 示例 2?

那样对它们进行分组

使用插件groupCssMediaQueries:

gulp.task('css', function() {
    gulp.src('./styl/*.styl')
        .pipe(stylus({
            use: nib()
        }))
        .pipe(groupCssMediaQueries())
        .pipe(gulp.dest('./public/css/'))
})