Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including @media queries as mixins with LESS

Mixins with LESS are really simple:

.some-rules() {
  /* some rules */
}
.some-class {
  .some-rules;
}

However, suppose I've got a ruleset within a media query, like:

@media (min-width: 800px) {
  .my_ruleset {
    /* more rules */
  }
}

How can I include such a ruleset as a mixin?

My motivation here is that I am using Bootstrap. I am trying to avoid semantically polluting my markup with its selectors, and would rather incorporate its rulesets as mixins. That's simple enough given the first example above, but I'm not sure how to incorporate the @media selectors.


EDIT

Specifically, here is a summary of the code I am trying to use as a mixin:

.container {
  .container-fixed();
}

// ...

@media (min-width: @screen-sm) {
  .container {
    max-width: @container-sm;
  }

  // ...
}

@media (min-width: @screen-md) {
  .container {
    max-width: @container-md;
  }

  // ...
}


@media (min-width: @screen-lg-min) {
  .container {
    max-width: @container-lg;
  }

  // ...
}
like image 1000
Dmitry Minkovsky Avatar asked Feb 16 '23 09:02

Dmitry Minkovsky


1 Answers

Just simply add:-

.my_ruleset {
    /* more rules */
  }

@media (min-width: 800px) {
  .my_ruleset;
}

If you want to add parameters to this for instance then:-

.my_ruleset(@myMargin:5px;) {
    margin:@myMargin;
  }

@media (min-width: 800px) {
  .my_ruleset(10px);
  /* New Rules*/
}
.
.
/* And so On */

Update:-

if you want to adapt this in a dynamic form take whole media query into mixin and play with it...

.container(
    @minSize:768px; 
    @maxSize:979px; 
    @myColor:green;
        /* So on */
) {
    @media (min-width: @minSize) and (max-width: @maxSize) {
      .my_ruleset {
            background-color:@myColor;
      }
      /* New Rules*/
    }
}

.container(0px,480px,black);
.container(481px,767px,blue);
.container(768px,979px,pink);
.container(980px,1200px,white);
.container(1700px,2200px,red);
like image 53
SaurabhLP Avatar answered Feb 26 '23 17:02

SaurabhLP