Using JavaScript operators in LESS (Should know)

Remember a previous exercise, where we created a number of squares on screen which were filled in with colors defined by LESS based on a given single color? Well, you can do something similar with text by using JavaScript operators. In this exercise we're going to show a number of headings on screen, which have been styled using operators to determine sizes and colors to be used.

How to do it…

Perform the following steps to get the the server to work out each value for each CSS style automatically:

  1. Open a copy of the template you created at the start of this chapter, add the following lines, and save it as test less operators.html:
    <body>
    <h1>Heading 1</h1>
    <h2>Heading 2</h2>
    <h3>Heading 3</h3>
    <h4>Heading 4</h4>
    <h5>Heading 5</h5>
    </body>
  2. Create a new document, add the following lines, and save this as operators.less:
    @mainColour: #631;
    @h1Size: 5em;
     
    h1 { color: @mainColour; font-size: @h1Size; }
    
    h2 { color: lighten(@mainColour, 10%); font-size: @h1Size * .8; }
    
    h3 { color: lighten(@mainColour, 20%); font-size: @h1Size * .6; }
    
    h4 { color: lighten(@mainColour, 30%); font-size: @h1Size * .4; }
    
    h5 { color: lighten(@mainColour, 40%); font-size: @h1Size * .2; }
  3. If all is well, you will see the following appear in your browser:
    How to do it…

How it works…

In this exercise we've used LESS to set the size and color to be used for each heading. The font-size value is worked out by multiplying a set value of 5em by 0.4, 0.6, or 0.8, depending on which heading size is being defined; this gives values of 2em, 3em, and 4em respectively. The color strength is set in a similar fashion, this time using the lighten command to progressively lighten the color from 10 percent to 40 percent, depending on which heading style is being defined. The same principle can be applied to other elements, such as buttons; we'll see how to do this in the next recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset