简体   繁体   中英

How to pass variables to LESS parametric mixin for gradient?

This should be a really easy thing to find but I am just not having any luck. I want to create a parametric mixing for a linear gradient, and have some variables with default values that I can change later by passing new variables when I call it. But for some reason it is giving me a syntax error when I try to pass variables.

Here is my mixin:

.gradient (@startColor: #adc7e7; @endColor: #ffffff) {
background-color: @endColor;
background: -webkit-gradient(linear, left top, left bottom, from(@startColor), to(@endColor));
background: -webkit-linear-gradient(top, @startColor, @endColor);
background: -moz-linear-gradient(top, @startColor, @endColor);
background: -ms-linear-gradient(top, @startColor, @endColor);
background: -o-linear-gradient(top, @startColor, @endColor);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='@startcolor', endColorstr='@endColor', GradientType=1);
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='@startColor',endColorstr='@endColor',GradientType=1);
}

When I call it like this, it's fine (it just uses the default colors)...

.test {background: .gradient; }

But when I call it like this to change the from or to colors, I get a syntax error when compiling...

.test {background: .gradient(#eeeeee,#ffffff); }
/* semicolon between the values don't work either */

I've tried all different ways of writing this and am not having any luck. The LESS documentation does not help at all, it is using @arguments variable which I can't see how to use for a gradient.

I'm using the LESS compiler (from incident57) for mac, version 2.8, build 969.

You should be including your mixin like this:

.test {
  .gradient; 
}

The following works for me:

@blue: blue;
@red: red;

body {
   .gradient(@blue, @red);
}

Codepen

More details in the parametric mixins doc

You have Two Main Issues

First , you are already including the background properties in your mixin, which is correct syntax, but makes it incorrect to call it like you are as the value of the property :

.test {background: .gradient(#eeeeee,#ffffff); }

Rather, it should be like this:

.test {.gradient(#eeeeee,#ffffff); }

Second , your two filter calls need to have the syntax for the variables called differently because they are nested inside of single quotes. So they should change to teh following (note the { brackets } around the name of the variables):

 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='@{startColor}', endColorstr='@{endColor}', GradientType=1);
  -ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='@{startColor}',endColorstr='@{endColor}',GradientType=1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM