CSS pre-processor with a possibility to define variables in a @media query

后端 未结 3 1457
悲&欢浪女
悲&欢浪女 2020-12-17 18:35

Currently, I am using LESS as my main CSS pre-processor. I have (and I am sure a lot of people have this need) to define variables in a @media query like:

相关标签:
3条回答
  • 2020-12-17 18:59

    what about:

    @media screen and (max-width: 479px) {
        .myElement(10px);
    }
    
    @media screen and (min-width: 768px) {
        .myElement(30px);
    }
    
    
    .myElement(@myVar) {
        .myElement {
            padding: @myVar;
        }
    }
    
    0 讨论(0)
  • 2020-12-17 19:10

    Let me answer more directly the question:

    "Is it possible to achieve this in any other CSS pre-processor, or we are doomed to override the .myElement within each media query?"

    The answer actually resides in the question. Because LESS (and other similar tools) is a "pre-processor," the @media means nothing to it at compilation time, because it is not looking at the media state of the browser for its preprocessing. The @media state is only relevant after the preprocessing, at which point any @someVariable has already been calculated. This is why what you are trying to do cannot work. Your @myVar can only be output as a single value in a CSS style sheet, and that output occurs before the browser state is ever evaluated by @media.

    So it does not have to do with the "global" or "local" scope of a media query, but the fact that LESS compiles the code into CSS utilizing the variables, and it is the CSS (not LESS) that pays attention to the @media query information.

    For some further discussion on building media queries with LESS in such a way that they are all together and not scattered throughout the code, see this question.

    0 讨论(0)
  • 2020-12-17 19:13

    You could refactor it out putting media queries in variables, and then using them within elements.

    Example:

    @phone: ~"screen and (max-width: 479px)";
    @tablet: ~"screen and (min-width: 480px) and (max-width: 767px)";
    @desktop: ~"screen and (min-width: 768px)";
    
    .myElement {
      @media @phone { padding: 10px; }
      @media @tablet { padding: 20px; }
      @media @desktop { padding: 30px; }
    }
    

    Which produces:

    @media screen and (max-width: 479px) {
      .myElement {
        padding: 10px;
      }
    }
    @media screen and (min-width: 480px) and (max-width: 767px) {
      .myElement {
        padding: 20px;
      }
    }
    @media screen and (min-width: 768px) {
      .myElement {
        padding: 30px;
      }
    }
    

    The whole make the media query an unparsed literal embed in a variable is not exactly pretty but also helps standardizing media queries.

    And it helps readability because all of the three behaviors of .myElement are contained in one definition and not changed somewhere else (which could be an entirely different file) making "debugging" hard.

    0 讨论(0)
提交回复
热议问题