1

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

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;
   });
}

任何帮助,将不胜感激!

4

1 回答 1

3

简短的回答:

不,你不能通过使用 Less mixins 得到你需要的输出(除非你最终做了一些非常丑陋的 hack)。

长答案:

更少,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;
   }
}

下面是一个片段,显示我所说的not valid 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;
}
于 2015-06-05T11:03:20.963 回答