Using JavaScript evaluation in LESS (Should know)

A powerful feature within Less is the ability to use basic JavaScript to generate CSS, such as using the screen.height function to determine how big your visitor's screen is. In this exercise we're going to demonstrate the power of using JavaScript within Less to draw a simple shape on screen, which uses the screen.height function of JavaScript.

Getting ready

For this exercise all we need is your text editor.

How to do it…

  1. We'll begin with opening a copy of the template we created at the start of this chapter; add the following lines, and save it as test Less javascript evaluation.html:
    <body>
      <div id="testbox">This is test number 1</div>
    </body>
  2. Create a new file, add the following lines of code, and save this as test Less javascript evaluation.less:
    @height: `screen.width`;
    
    #testbox { background-color: orange; height: 100px; width: ~`@{width}/2 + "px"`; }
  3. Test the HTML file in your browser; you should see something like the following screenshot:
    How to do it…

How it works…

Although this is an overly simplified example, it serves to illustrate how you can use JavaScript to determine how big the box should appear. The use of LESS code is based around standard JavaScript code, but must use the ~`…` format to ensure that it is correctly interpreted by the compiler:

#testbox { 
  background-color: orange; 
  height: 100px; 
  width: 640px; 
} 

Tip

Note that using JavaScript in CSS can produce some very powerful effects; you should take care over using it, as it is open to abuse, and can be a security risk on your site if you are not careful!

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

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