【问题标题】:Less with calc() function in a string var在字符串 var 中使用 calc() 函数
【发布时间】:2014-04-29 00:28:01
【问题描述】:

我尝试在 LESS 中执行此操作 @screen-lg : 1200px;

@laptop : ~"only screen and (min-width: 768px) and (max-width: @{calc(screen-lg - 1px)})";

定位到 1199 像素。但它不喜欢它。

是否可以在字符串 var 中使用 calc() 函数进行操作?

谢谢。

【问题讨论】:

    标签: css less media-queries


    【解决方案1】:

    我认为你不需要任何calc。你可以得到你想要的:

    1

    @screen-lg: 1200px;
    @screen-lg-max: (@screen-lg - 1);
    
    @laptop: ~"only screen and (min-width: 768px) and (max-width: @{screen-lg-max})";
    
    @media @laptop {
        color: red;
    }
    

    2

    @screen-lg: 1200px;
    
    @laptop: ~"only screen and (min-width: 768px) and (max-width:" (@screen-lg - 1) ~")";
    
    @media @laptop {
        color: red;
    }
    

    3

    (小于 1.7.0):

    @screen-lg: 1200px;
    
    .laptop(@styles) {
        @media screen and (min-width: 768px) and (max-width: (@screen-lg - 1)) {
            @styles();
        }
    }
    
    .laptop({
        color: red;
    });
    

    以上所有三个 sn-ps 都会生成以下 CSS:

    @media only screen and (min-width: 768px) and (max-width: 1199px) {
      color: red;
    }
    

    【讨论】:

    • 除非我误解了 OP,否则这应该是公认的答案。
    【解决方案2】:

    媒体查询必须在运行时进行评估,而 less 通常在构建时编译。要执行此类操作,您可能需要客户端 Javascript 版本 http://lesscss.org/#client-side-usage ,并且每次调整窗口大小时都重新编译更少的脚本,因此使用 less 可能没有意义,而且您会做得更快(更干净) 在 Javascript 中。

    话虽如此,如果您尝试这样做,您可能不得不向后执行(即将您的 less 变量包装在媒体查询中)。但我完全不确定这是否有意义。

    【讨论】:

      【解决方案3】:

      由于 Less 是在构建时解析的,因此您可以只使用内置的数学功能。不需要计算。这工作得很好:

      @screen-lg : 1200px;
      @laptopsize: @screen-lg - 1px;
      
      @laptop: ~"only screen and (min-width: 768px) and (max-width: @{laptopsize})";
      
      @media @laptop {
          div{background: black;}
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 2016-03-29
        • 1970-01-01
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        相关资源
        最近更新 更多