嵌套媒体查询输出

Nested media queries output

我最近从 SASS 切换到 Less(工作)并且想知道是否可以从 Less 获得这个输出(使用混合):

footer {
  width: 768px;
   @media only screen and (min-width: 992px) {
    width:900px;
   }
   @media only screen and (min-width: 1200px) {
     width:1200px;
   }
}

我似乎只能像这样在单独的断点中获得输出(而不是在选择器下):

@media only screen and (min-width: 720px) and (max-width: 959px) {
 footer {
  width: 768px;
 }
}
@media only screen and (min-width: 960px) and (max-width: 1199px) {
 footer {
   width: 3939px;
 }
}

这是我一直在使用的 mixin:

.respond-to(@respondto; @rules) when (@respondto = "lg") {
  @media only screen and (min-width: 1200px) {
    @rules();
  }
}
.respond-to(@respondto; @rules) when (isnumber(@respondto)) {
  @media only screen and (min-width: @respondto) {
   @rules();
  }
}

然后像这样使用它:

div.class {
   .respond-to(120px, {
     float:left;
   });
   .respond-to("lg", {
     float:none;
   });
}

如有任何帮助,我们将不胜感激!

简答:

不,您无法通过使用 Less 混入获得所需的输出(除非您最终做了一些非常丑陋的黑客攻击)。

长答案:

Less、SASS 等是(如您所知)CSS 预处理器。它们的主要用途是允许编写 DRY 代码和更快地创建 CSS(还有其他好处,但这些是使用它们的主要原因)。因此,如果预处理器产生的输出不是有效的 CSS 代码,那么它就没有用了——因为最终在您的项目中实际使用的是 CSS。

下面的代码片段无效 CSS 因为不支持这样的结构,所以 Less 永远不会产生那样的输出。

注意:然而,这是一个有效的 Less 代码结构,因为 Less 支持选择器和媒体查询的嵌套。

footer {
  width: 768px;
   @media only screen and (min-width: 992px) {
    width:900px;
   }
   @media only screen and (min-width: 1200px) {
     width:1200px;
   }
}

下面是一个片段来说明我所说的 无效 CSS 的意思。检查媒体查询如何影响 color 而不是 background.

/* Invalid CSS */
footer {
  background: beige;
   @media only screen and (min-width: 600px) {
    background: blue;
   }
   @media only screen and (min-width: 700px) {
     background: green;
   }
}

/* Valid CSS */

footer {
  color: red;
}
@media only screen and (min-width: 600px) {
  footer{
    color: blue;
  }
}
@media only screen and (min-width: 700px) {
  footer{
    color: green;
  }
}
<footer>This is a footer</footer>


来到你的 mixin,你可以像下面的代码片段一样重写它

.respond-to(@respondto; @rules){
     & when (@respondto = "lg") {
      @media only screen and (min-width: 1200px) {
        @rules();
      }
    }
    & when (isnumber(@respondto)) {
      @media only screen and (min-width: @respondto) {
       @rules();
      }
    }
}

或喜欢下面的代码,让您的代码保持干爽。

.respond-to(@respondto; @rules){
  .set-width(@respondto); // call to set the media query width depending on input
  @media only screen and (min-width: @width) {
    @rules();
  }
}
.set-width(@respondto) when (@respondto = "lg") {
  @width: 1200px;
}
.set-width(@respondto) when (isnumber(@respondto)) {
  @width: @respondto;
}