Compiling back to LESS from CSS (Should know)

In this recipe we're going to see how you can create Less code, based on an existing CSS stylesheet.

Getting ready

For this exercise, all you need is your browser. This will need to be the latest version, as this exercise will not work in some browsers, such as IE8 or below. For the purpose of this exercise, I will assume you are using the latest version of Firefox.

How to do it...

  1. Let's start by browsing to css2less.cc, and remove all of the code shown in the CSS half of the window. The Less window will automatically update itself when you make any changes.
  2. In the left-hand side window, add the following CSS code:
    #div { color: blue; }
     
    #div #title { background: #d24444; }
  3. Notice how the contents of the Less section have changed as shown in the following screenshot:
    How to do it...

How it works...

The site was designed around the css2less script written in Ruby by Marcin Kulik, and which has since been refactored and converted to gem format by Thomas Pierson. The script used on this site is actually very small; it reads in the contents of the existing CSS file (or, in this instance, the contents of the CSS window on the right-hand side of the screen), then creates a new instance of the Css2Less::Convertor class, and parses the content with the results appearing on screen almost instantaneously.

There's more...

While this is a great way to learn how to convert CSS styles to their Less equivalents, it is not perfect. There is one drawback you need to be aware of: there is a limit on the number of characters (set at 50,000) that can be converted; the conversion process doesn't work so well on larger or more complex files. For example, if you try converting back the 2600+ lines for Wordpress' Twenty Eleven theme, it will most likely fail!

You will find that there is a limit in what the less2css.cc site can manage. It works best on styles that could be nested, but not on styles that could use mixins or variables to help reduce the code. It's a good tool to use when starting out, but you will probably find yourself moving away from using it once you become more accustomed to spotting where Less can help reduce code.

There is one area left for us to look at before we start to write some Less code. If we make a change to our Less code, you would naturally need to refresh the page; in some instances this may not always work correctly, as we will see in the next exercise.

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

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