Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LESS Mixin with variable and content

Tags:

css

less

So in sass, the mixin can do:

@mixin bp($point) {
  @if $point == papa-bear {
    @media (max-width: 1600px) { @content; }
  }
  @else if $point == mama-bear {
    @media (max-width: 1250px) { @content; }
  }
  @else if $point == baby-bear {
    @media (max-width: 600px)  { @content; }
  }
}

And can be used as:

.img {
  width: 33.33%;
  @include bp(baby-bear) {
    width: 100%;
  }
}

Is there a similar way in LESS to dynamically generate the css? Especially passing a block of stylings like what the @content does here.

like image 871
ccChloeX Avatar asked Aug 07 '14 19:08

ccChloeX


People also ask

What can be passed to a LESS mixin?

Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.

What is the difference between mixin and variable?

I have been doing some googling and I currently understand the difference being that a variable stores a single line of information whereas, a mixin stores multiple lines of variables.

How do you represent a variable in LESS?

Defining a variable: Variables in Less are represented with an at (@) sign. We can assign a value using a colon (:).


1 Answers

Indeed you can use Passing Rulesets to Mixins as already mentioned by @seven-phases-max.

For your break-points (bear types) in Less

You can use pattern-matching:

.bp(papa-bear,@rules) {
@media (max-width: 1200px) {@rules();}
}
.bp(mama-bear,@rules) {
@media (max-width: 800px) {@rules();}
}
.bp(baby-bear,@rules) {
@media (max-width: 600px) {@rules();}
}

.img {
  width: 33.33%;
  .bp(baby-bear; { width: 100%;});
}

Or mixin guards:

.bp2(@point,@rules) {
& when(@point = baby-bear) {
    @media (max-width: 600px) {@rules();}
}
& when(@point = mama-bear) {
    @media (max-width: 800px) {@rules();}
}
& when(@point = papa-bear) {
    @media (max-width: 1200px) {@rules();}
}
}

.img {
  width: 33.33%;
  .bp2(baby-bear; { width: 100%;});
}

In your example you can also write a single mixin:

.bp3(@point,@rules) {
  @query: ~"(max-width: @{point})";
  @media @query {@rules();}
}

.img {
  width: 33.33%;
  .bp3(600px; { width: 100%;});
}

Or when you have to reuse your bear types:

@baby-bear-max-width: 600px;
@mama-bear-max-width: 800px;
@mama-bear-max-width: 1200px;

.bp4(@bear,@rules) {
  @query: ~"(max-width: @{@{bear}-max-width})";
  @media @query {@rules();}
}

.img {
  width: 33.33%;
  .bp4(baby-bear; { width: 100%;});
}
like image 94
Bass Jobsen Avatar answered Oct 01 '22 18:10

Bass Jobsen