Search code examples
lessmixinsless-mixins

How to declare same style for @media and descendant selector?


I need to define same style for elements under a media query and descendant by another class.

Perfect solution in LESS could be the following [pseudo-code]:

.foo
{
  color:red;

  .example &,
  @media (min-width:800px)
  {
    color:blue;
  }
}

that should be desirable that would be compiled into:

.foo {
  color: red;
}
.example .foo {
  color: blue;
}
@media (min-width: 800px) {
  .foo {
    color: blue;
  }
}

THIS SYNTAX IS INCORRECT but, do you have some suggestion to solve my problem?


Solution

  • Thanks to @seven-phases-max suggestion, I finally found a possible solution using Detached Ruleset:

    @screen-xs: 480px;
    @screen-sm: 769px;
    @screen-md: 992px;
    @screen-lg: 1200px;
    
    .MEDIAQUERY(@only-media, @min-max, @size, @RULES) 
    {
      @screen-width:~"@{screen-@{size}}";
    
      @mediaQuery: ~"screen and (@{min-max}-width: @{screen-width})";
    
      @media @mediaQuery { @RULES(); }
    
      & when (@only-media = false) {
        .@{size} &       { @RULES(); }  
      }
    }
    
    .foo_media-and-class
    {
      color:red;
    
      .MEDIAQUERY(@only-media:false, @min-max:max, @size:md,
        { 
            color:blue;
        }
      );
    
      .MEDIAQUERY(@only-media:false,  @min-max:min, @size:lg,
        { 
            color:yellow;
        }
      );
    }
    
    .foo_only-media
    {
      color:red;
    
      .MEDIAQUERY(@only-media:true,  @min-max:max, @size:md,
        { 
            color:blue;
        }
      );
    
      .MEDIAQUERY(@only-media:true,  @min-max:min, @size:lg,
        { 
            color:yellow;
        }
      );
    }
    

    This solution go beyond and offer other options:

    • Possibility to set a custom value of screen width for media query,
    • Pass MIN/MAX value of property used in media query (Try to pass "max" instead of "min" calling .MEDIAQUERY mixin)
    • Toggling generation of simple media query or media query + descendant selector, through @only-media boolean.