你能用LESS mixins创建自定义断点吗?

Bry*_*son 8 css less media-queries

大多数时候,我使用带有预设断点的LESS变量进行媒体查询,如下所示:

@s-max : ~"screen and (max-width: 40em)";
@m-max : ~"screen and (max-width: 50em)";
@l-max : ~"screen and (max-width: 60em)";

USAGE

.some-class {
    color: red;

    @media @s-max {
       color: blue;
    }
}
Run Code Online (Sandbox Code Playgroud)

但有时,我希望能够在我的.less样式表中引用任意断点,而无需在单独的mixin文件中设置新的预设值.

你可以在SASS中做到这一点.mixin看起来像这样:

@mixin bp-min($canvas) {

    @media only screen and (min-width:$canvas) {@content;}
}

USAGE

@include bp-min(750px) {

//responsive styling for min-width of 750px

}
Run Code Online (Sandbox Code Playgroud)

在LESS中,我想象等效的mixin看起来像这样:

.bp-min(@min) {

    @media only screen and (min-width:@min)...
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,LESS中缺少{@content}参数,它抓住了开发人员输入的其余样式.我喜欢SASS,但我不能在工作中使用它.

有谁知道这个问题的基于LESS的解决方案?

fre*_*red 12

它现在类似于SASS

1.7.0(2014-02-27)开始,您现在可以使用@rules代替时髦的@content.

例如:

.breakpoint-small(@rules) {
  @media screen and (min-width: 40em) { @rules(); }
}

ul {
  width: 100%;
  .breakpoint-small({
    width: 50%;
  });
}
Run Code Online (Sandbox Code Playgroud)

输出,如预期:

ul {
  width: 100%;
  @media screen and (min-width: 40em) {
    width: 50%;
  }
}
Run Code Online (Sandbox Code Playgroud)

差异是:

  • 函数将@rules作为参数
  • 调用函数时的附加括号
  • '' 语法而不是'@include'

这可以与一个额外的参数结合使用,以提供相当于一点点sass的语法:

.breakpoint(@size, @rules) {
  @media screen and (min-width: @size) { @rules(); }
}

@large: 60em;
ul {
  .breakpoint(@large, {
    width: 50%;
  });
}
Run Code Online (Sandbox Code Playgroud)

编辑:说实话,我更喜欢一种更简单的方法:

@break-large: ~"screen and (min-width: 60em)";
ul {
  @media @break-large {
    width: 50%;
  }
}
Run Code Online (Sandbox Code Playgroud)

资料来源:我也在家里使用sass而在工作中使用较少


Sco*_*ttS 5

使用模式匹配

我相信这可以实现你想要的:

/* generic caller */
.bp-min(@min) {
    @media only screen and (min-width:@min) {
      .bp-min(@min, set);
    }
}

/* define them */
.bp-min(750px, set) {
  test: (@min - 300px);
}
.bp-min(400px, set) {
  test: (@min - 100px);
}

/* call them */
.bp-min(750px);
.bp-min(400px);
Run Code Online (Sandbox Code Playgroud)

输出CSS

@media only screen and (min-width: 750px) {
  test: 450px;
}
@media only screen and (min-width: 400px) {
  test: 300px;
}
Run Code Online (Sandbox Code Playgroud)

通过set为各种大小定义模式mixin,然后在通用.bp-min(@min)mixin中使用该模式,我相信我们在SCSS中拥有与LESS相同的抽象,代码略多,因为我相信SCSS在一个@include语句中定义和调用,而在这里我们需要两个.