【问题标题】:How to convert this SCSS mixin to LESS?如何将此 SCSS mixin 转换为 LESS?
【发布时间】:2014-01-17 05:43:47
【问题描述】:

我习惯用 SCSS 编码,但对 LESS 很陌生。

我在 SCSS 中有以下代码,但想知道如何在 LESS 中编写。

这里是 SCSS 代码...

@mixin posL($property, $value) {
   {$property}: $value;
}

.box {
   width:200px;
   height:200px;
   background:red;
   position:absolute;
   @include posL(left, 100px);
 }

到目前为止,我在 LESS 中有类似的东西,但我必须声明选择器...

.posL(@property: 100px, @value: 2px) {
    left: @property;
    -rtl-left: @value;
}

.box {
    width:200px;
    height:200px;
    background:red;
    position:absolute;
   .posL(200px);
 }

有没有更好的方法来编写我的 LESS 代码,以便 mixin 中的选择器保持通用(未指定)?

【问题讨论】:

    标签: sass less


    【解决方案1】:

    LESS 1.6+ 更新

    现在和the 1.6 update几乎是直接映射,像这样:

    .posL(@property, @value) {
       @{property}: @value;
    }
    
    .box {
       width:200px;
       height:200px;
       background:red;
       position:absolute;
       .posL(left, 100px);
     }
    

    CSS 输出

    .box {
      width: 200px;
      height: 200px;
      background: red;
      position: absolute;
      left: 100px;
    }
    

    原始答案(1.6 之前)

    虽然there is discussion about it,但目前没有真正的方法在 LESS 中使用动态属性名称(无论是前缀还是完整的属性名称)。

    我推荐一个通用的 mixin,它带有一个嵌套的、受保护的 mixin 用于逻辑。这仍然为您提供了对特定属性的选择,但确实需要一些更明确的代码来设置它。比如:

    .posL(@property, @value) {
       .getProp(left) {
          left: @value;
        }
       .getProp(-rtl-left) {
          -rtl-left: @value;
       }
       .getProp(@property);
    }
    

    然后使用它非常类似于您如何使用 SASS 版本:

    .box {
       width:200px;
       height:200px;
       background:red;
       position:absolute;
       .posL(left, 100px);
     }
    

    编译为:

    .box {
      width: 200px;
      height: 200px;
      background: red;
      position: absolute;
      left: 100px;
    }
    

    【讨论】:

    • 感谢您的确认,我在做一些额外的研究时也发现了同样的情况,这些解决方案和讨论非常有帮助。我会将其标记为正确答案,因为它似乎是正确的
    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2014-07-07
    • 2013-05-10
    • 2017-11-29
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多