How work mixins with arguments in LESS?

Mixins allow to inherit of a group of properties  from one into another rule-set. You can use class for mixins or identifactor. In the our example we use class as mixins.
The HTML code:

<!DOCTYPE html>
<html>
    <head>
        <title>Animals</title>
        <link rel="stylesheet" href="myStyle.css"  type="text/css" >
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>My favorite animals</h1>
        <div class='firstBox'><p>Dogs</p></div>
        <div class='firstBox'><p>Hamsters</p></div>
        <div class='middleBox'><p>Leos</p></div>
        <div class='lastBox'><p>Tigers</p></div>
    </body>
</html>

The LESS file with mixins:

@backgroundBox: #ffdd11;

.topBox (@x:500px, @y:90px )
{
 width:@x ;
 height:@y ;
 color:blue;
 background-color:@backgroundBox ;
}
    .firstBox 
    { 
    .topBox( 180px ,30px ) ;
    color:purple;    
    }
    
    .middleBox 
    {  
    .topBox( 600px / 2 ) ;  
    } 
    
    .lastBox 
    { 
    .middleBox ; 
    color:blue;
    background-color:@backgroundBox + #222 ;
    }

The mixins class or identifier may use arguments, but it doesn’t required. In the definition of our mixins class(topBox) get two arguments. The arguments can have also default values. So if you use only name of this class mixins or name with empty brackets, the default values will be use. The next class firstBox use in LESS file with two values of arguments(180px and 30px). The middleBox use topBox mixins class with only one argument(600px/2), so value of second argument is assigned by default value. Notice, that this argument using an expression. In LESS you can use expressions as values of  variables or arguments.  And the lastBox class use middleBox class to use properties this class. The background-color property defined in topBox class  uses value of  the backgroundBox variable. The middleBox inherits this property with this defined value. However, you can change this value, for example in lastBox class this property is use with new value. Notice, that you for rgb color can use expression adding new rgd color.

Look at the result:

 

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.