【问题标题】:Nested media queries output嵌套媒体查询输出
【发布时间】:2015-06-05 19:07:56
【问题描述】:

我最近从 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;
   });
}

任何帮助将不胜感激!

【问题讨论】:

  • mixin 的输出(编译时)将是 CSS 代码,恐怕第一个示例(媒体查询嵌套在元素中)不是有效的 CSS。
  • 我已添加我的评论作为答案,因为“否”是该问题的有效答案,我有更多空间来展示如何使您的 mixin 变得更干燥。

标签: css less less-mixins


【解决方案1】:

简答:

不,您无法通过使用 Less mixins 获得所需的输出(除非您最终做了一些非常丑陋的 hack)。

长答案:

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

下面的 sn-p 不是有效的 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;
   }
}

下面是一个 sn-p,用于显示我所说的 无效 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,你可以像下面的 sn-p 那样重写它

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

【讨论】:

  • 感谢您的澄清!
猜你喜欢
  • 2013-04-13
  • 2011-12-01
  • 2015-07-18
  • 2014-02-19
  • 1970-01-01
  • 2015-08-27
  • 2018-01-24
  • 2013-04-28
  • 1970-01-01
相关资源
最近更新 更多