Is there a LESS equivalent to this SASS functional

2019-09-01 08:30发布

问题:

I'm working my way through some stuff which includes media queries and lots of repetitive code - even with mixins.

I came across a website that included this SASS code:

html{
  @include responsive("font-size", 11px,
    (
       600px: 12px,
       800px: 13px,
      1180px: 14px,
      1300px: 15px,
      1750px: 16px,
      1900px: 17px,
      2100px: 18px,
      2400px: 19px
    )
  );
}

Unfortunately, there was no further reference to "responsive" so I don't know much about it, but I believe the goal is to create media query output with the rules.

I know about rulesets in LESS, but is it possible to chain rulesets like they have accomplished here?

Thanks in advance.

回答1:

This might be your best bet with respect to Less. Basically, we are using a 2D array list (with the media size and property value) as a parameter to the mixin. Please refer inline comments for further explanation.

@array: 600px 12px, 700px 13px, 800px 14px; /* 2D array with media size & value */
.responsive(@property; @defaultValue; @array){

    @{property}: @defaultValue; /* default setting*/

    .loop-media-query(@index) when (@index > 0){ /* loop for media query */
        @mediaSize: extract(extract(@array,@index), 1); /* first array val is media size */
        @font-size: extract(extract(@array,@index), 2); /* second array val is property value */

        @mediaQuery: ~"(min-width: @{mediaSize})"; /* form the media query */

        @media @mediaQuery{ /* output the settings */
            @{property}: @font-size;
        }

        .loop-media-query(@index - 1);
    }

    .loop-media-query(length(@array));
}

.output{
    .responsive(font-size; 11px; @array);
}

Compiled CSS:

.output {
  font-size: 11px;
}
@media (min-width: 800px) {
  .output {
    font-size: 14px;
  }
}
@media (min-width: 700px) {
  .output {
    font-size: 13px;
  }
}
@media (min-width: 600px) {
  .output {
    font-size: 12px;
  }
}


标签: sass less