简体   繁体   中英

LESS CSS parametric mixin default null value does not work

I have lesscss mixin for box-shadow like this :

.box-shadow(@x, @y, @blur, @color, @addit: ''){
    -webkit-box-shadow: @x @y @blur @color @addit;
    -moz-box-shadow: @x @y @blur @color @addit;
    box-shadow: @x @y @blur @color @addit;
}

As you seen, There is a parameter @addit that set to '' as default.

It's work fine when I give @addit a value like : .box-shadow(0, 0, 2px, #1361aa, inset) , But why if parameter for @addit not filled, then it doesn't work? And how to fix it?

Help, thanks for advance.

Escape the empty string as your default

You need to set the default value to ~'' so it is an escaped string.

LESS

.box-shadow(@x, @y, @blur, @color, @addit: ~''){
    -webkit-box-shadow: @x @y @blur @color @addit;
    -moz-box-shadow: @x @y @blur @color @addit;
    box-shadow: @x @y @blur @color @addit;
}

.test{
   .box-shadow(0, 0, 2px, #1361aa)
}

CSS

.test {
  -webkit-box-shadow: 0 0 2px #1361aa ;
  -moz-box-shadow: 0 0 2px #1361aa ;
  box-shadow: 0 0 2px #1361aa ;
}

You can't use '' as it will add an invalid parameter to box-shadow. This is the generated output for .box-shadow(2px, 2px, 5px, #F00);

#myDiv {
  -webkit-box-shadow:2px 2px 5px #ff0000 '';
  -moz-box-shadow:2px 2px 5px #ff0000 '';
  box-shadow:2px 2px 5px #ff0000 '';
}

As you can see, LESS CSS supports strings and empty strings as parameters, however, CSS does not recognize this, and discards this as an invalid style.

One way you could do it is simply using two mixins with same name but different number of parameters (similar to overloading):

.box-shadow(@x, @y, @blur, @color) {
    -webkit-box-shadow: @x @y @blur @color;
    -moz-box-shadow: @x @y @blur @color;
    box-shadow: @x @y @blur @color;
}
.box-shadow(@x, @y, @blur, @color, @addit) {
    -webkit-box-shadow: @x @y @blur @color @addit;
    -moz-box-shadow: @x @y @blur @color @addit;
    box-shadow: @x @y @blur @color @addit;
}

Tested this and works with the following:

.box-shadow(2px, 2px, 5px, #F00);
.box-shadow(2px, 2px, 5px, #F00, inset);

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