How to create a less function (mixin) and use it for implementing beautiful and customized CSS box-shadows

Less supports the creation of pseudo-functions that can be used as CSS-classes in your less files. Doing this way you can save multiple keystrokes, automate your stylings and avoid syntax errors.

Lets take a look at a function that automates the creation of CSS box-shadows and supports new browsers by making use of browser prefixes.

1
2
3
4
5
.box-shadow (@orientation: inset, @horizontalLength: 0px, @verticalLength: 0px, @blur: 0px, @spread: 0px, @shadowColor: white, @opacity: 0.5) {
    -webkit-box-shadow: @orientation @horizontalLength @verticalLength @blur @spread fade(@shadowColor, @opacity);
    -moz-box-shadow: @orientation @horizontalLength @verticalLength @blur @spread fade(@shadowColor, @opacity);
    box-shadow: @orientation @horizontalLength @verticalLength @blur @spread fade(@shadowColor, @opacity);
}
  • The pseudo-function also known as mixin in less-context is called box-shadow

  • The first parameter of the function is the orientation. The supported values are outline and inset

  • The second parameter is the horizontal length of the shadow

  • The third parameter is the vertical length of the shadow

  • The fourth parameter is the blur effect of the shadow

  • The fifth parameter is the spread effect of the shadow

  • The sixth parameter is the color of the shadow

  • The seventh parameter is the opacity of the color of the shadow

  • The values defined in the function definition are the default values used when we use the function when a value is not defined.

You also see the use of the fade() function which is a less-function. By using this function we can define the opacity (transparency) of the color of an element. The first parameter of the function is the color and the second is the opacity.

The .box-shadow function makes use of the -webkit and -moz browser prefixes to support older versions of webkit and mozilla browsers.

You can define the previous code in a “common”-less file and use it in other files like that:

1
2
3
4
#test-div {
    /* Other CSS-rules of the test-div */
    .box-shadow (inset, 0px, 0px, 3px, 5px, #000, 0.2)
}

The previous less code snippet generates the following css code:

1
2
3
4
5
6
#test-div {
    /* Other CSS-rules of the test-div */
    -webkit-box-shadow: inset 0px 0px 3px 5px rgba(0,0,0, 0.2);
    -moz-box-shadow: inset 0px 0px 3px 5px rgba(0,0,0, 0.2);
    box-shadow: inset 0px 0px 3px 5px rgba(0,0,0, 0.2);
}
comments powered by Disqus