Grow your CSS skills. Land your dream job.

Using LESS as a Live CSS Engine

Published by Guest Author

The following is a guest post by Andrew Powers of PageLines. Andrew wrote to me about how they use LESS in their product and how they think it's better than Sass for what they do. In complete honesty, I still disagree (they are using an unofficial PHP port of LESS, and there is an unofficial PHP port of Sass also), but I can't argue that they way they use it is pretty cool and works for them. This is Andrew explaining that.

There has been a lot of talk recently about using LESS/Sass as preprocessors for creating cleaner, cross-browser friendly CSS faster and easier than we could before. And from my own experience I can tell you that once you go to one of these languages, you’ll have so much fun that you won’t be going back to plain CSS.

The problem with these languages, however, is the word ‘preprocessor.’

The idea of a preprocessor is there is this ‘processing’ step between the code you write and the code you use on your site. That’s kind of a hassle. Also it prevents us from using variables or functions dynamically, which might be useful if you have users customizing the presentation of your code (like in a WordPress theme).

Well, live processing LESS in production is very possible, and here is how we’re using it to solve some big problems at our company.

About PageLines

pagelines-loves-less

PageLines makes a ‘drag and drop’ framework, built on WordPress, intended to make building professional websites easy.

Trying to keep the professional, yet easy (typical users shouldn’t have to write *any* code), has created a few engineering challenges which LESS has helped solve.

Use Case

The PageLines framework is built on WordPress (in PHP). In considering this solution we had several goals. For example, we wanted to:

  • Allow CSS to be customized based on user options inside the framework
  • Organize and compartmentalize CSS better without upping performance killing HTTP requests
  • Create better, more cross-browser designs, faster and easier without having to deal with a new ‘preprocessing’ step in our workflow

Why LESS for Live Processing? (Not SASS/Compass)

Chris wrote an interesting article on the merits of Sass vs. LESS. However, there are a couple thoughts left out that shift things in the favor of LESS for live processing for us. Specifically LESS was designed in JavaScript, the developer friendly language, and was also created to be used live. Most importantly, it compiles 6x faster than SASS. Jacob Thornton, architect of the popular Bootstrap by Twitter, has some more input on the debate here.

While the original live less.js approach has too much of a delay in production, it still helps seal the deal for LESS when we’re talking about using it in production instead of as a preprocessor. We ultimately used a special PHP port of Less.js to accomplish our goal, more on that in a second.

As a sidenote, it’s theoretically possible to use SASS ‘live’ if you’re developing in a Ruby on Rails environment. We haven’t actually tested this, so I’m not sure about the performance or bottlenecks using that approach.

How we implemented it

For us the the key to executing a live LESS engine was this port of the LESS processor to PHP (link) which allowed us to parse and cache LESS files based on user action on our server. To get this working the framework just does the following.

  • Grabs all the LESS files throughout the framework and adds them to a PHP variable
  • Uses the above PHP script to parse the LESS into CSS and puts it in a variable
  • Outputs the CSS to a file which is cached both on the server and on visitors browsers
  • The process is run again whenever a user saves their settings or installs a new extension

Code Example

This isn’t the actual code we used, but should give you a general idea.

$parser = new lessc(); // Start new object from PHP Less script
$less_code = file_get_contents(‘/path/to/whatever.less’); // Grab LESS
$processed_css = $parser->parse($less_code); // Process to CSS
file_put_contents(‘path/to/css-file.css’, $processed_css); // Write CSS
echo “<link rel='stylesheet' href='http://url/to/css-file.css' type='text/css' media='all' />”; // Link CSS in page

Results

dynamic-colors
Changing background color in the framework. Highlights and contrast element colors are calculated using LESS.

Control - Dynamic Colors and Typography

One of the coolest things about implementing LESS inside of the framework is that we’re able to dynamically control colors and typography based on user selections. This allows us to design things well, while still giving users the ability to customize colors and type.

Options - LESS Option for Users

lessoption

Users are able to actually add their own LESS in the admin options panel. They can use common variables for the background color or main fonts. This has been a feature that users love and can use to create more cross-browser, robust customization of the framework.

Organization - Several Files Into One

files-to-one

Using a processor for the LESS allows us to have all our css/less files organized by type, then grouped together at runtime into a single ‘compiled-css’ file. Definitely makes it easier to find what we’re looking for.

Optimization - Cleaner, Faster, Cross-Browser CSS

mixins

Because we can use nested selectors & mixins the code we are writing is much cleaner. While this is the same as when using a preprocessor, not having to deal with finding all the files and compiling allows us to use this without the hassles.

Comments

  1. pk
    Permalink to comment#

    Until Less loses the curly braces and semi-colons, you’ll have to pry Sass out of my cold, dead fingers. I can scan 100 lines of Sass and see what is nested under what way quicker than Less, and I’ve worked in both for some time. Not to mention that Sass is sexier to look at.

    • lozandier@gmail.com
      Permalink to comment#

      Haha, love that first statement. I can’t imagine life without the indented-oriented version of SASS either.

      It’s really interesting their use of LESS as a live CSS Engine. To be honest, I thought that WAS the main reason LESS was built using JavaScript though.

      Interesting point about it should theoretically work doing the same thing with SASS, does anyone have any resources on doing that?

  2. Permalink to comment#

    I’m sure I’m one of the very few (I haven’t read a post about someone else so far either), but I honestly just can’t use any of those CSS preprocessors, I really don’t like to “javascriptify” my CSS.

    For all that I’ve read I think the ones that use (and love) CSS preprocessors have a very strong knowledge of web programming (they know a shitload of PHP and JavaScript, etc.), so they get along with the way the CSS is written in the preprocessors. I’m more a Web Designer than a Web Programmer.

    I have a very efficient way of writing my CSS and organizing it, indent it, comment it. None of those things LESS or SASS/Compass gives me, they format the CSS their own way (not sure if there’s a way to customize how the final CSS is created). Also, I lose the auto-complete feature when typing properties, which is absolutely necessary to be efficient.

    If I need to change a color across a CSS file (not sure why I’d do that though), there’s nothing search & replace can’t accomplish in less than 1-2 seconds. Then CTRL+S. Total time 2.5 seconds.

    This leads me to ask then: Is there an editor out there that supports auto-complete when using LESS – SASS/Compass? I’ve tried Notepadd++ and Dreamweaver CS5-6 and they don’t.

    I wish I worked with programmers with the level of knowledge of Andrew and team, wow.

    Thanks.

    • cir
      Permalink to comment#

      Ricardo, it’s a matter of time getting used to it. The beauty of LESS is that it’s just CSS, but with lots of enhancements, so you can for example write a file in pure CSS, save it as .less and it’ll compile just fine. The way you write LESS largely depends on your editor. I use Vim with a couple plugins and I get all the goodies, syntax highlighting, auto-completition, and live compile, so as soon as you save you get the compiled CSS right away. Once you get your LESS workflow organized it’s just like writing CSS but with waaaaay more features. Why would you wanna waste 2.5 seconds searching an replacing when you can do it in half a sec by just changing the color once?

    • Permalink to comment#

      Ricardo… You make a good point….and it is sort of the reason why I have been hesitant to go down the preprocessor path…I like to control the output of my CSS and optimize it for speed…I loose control with these preprocessors…

      Plus as you were saying…these Preprocessors seem to be loved by those that love the command line…Cir said he uses “Vim” … a Unix / Linux text editor…great…I am sure designers must love the user interface of a Unix text editor…anyways…this tells me that these processors are geared more to the “developer” types as opposed to the design types…

      I always ask why add this extra layer of PHP scripts…hacks and other things to a format (CSS) that already allows you to write a single file and have it apply across thousands of pages…brilliant…why make it more complex…

      People say look at PHP…it does the same with HTML (it preprocesses it)…true…but that was because without it one would have to manually or write scripts to change hundreds or thousands of separate HTML files if a global change was needed….I highly doubt there are many sites that we work on that have any more than half a dozen style sheets total…and that is pushing it…

      Plus I love HTML / CSS and JavaScript because I can open Notepad save it as a .js .html or a .css and load it in a browser…no server this or process that…write a quick script test and review…simple…which is why these simple languages are the most popular languages of the web…

    • Permalink to comment#

      Hey Ricardo, if you want an editor that has SASS/LESS support, consider sublime text 2 using package control you can add virtually ANY package to give Sublime all the support you need. Specifically the LESS and LESS Build modules, which gives you things like tab completion, code highlighting, LESS compilation, etc.

      As far as I’ve seen, you format your SASS/LESS file as you normally would any other CSS project. The benefit to LESS for me is I can configure it to handle things like prefixing my markup, automagically minifying my files, all in one build step. Saves me an exorbitant amount of time overall. The package build on save helps with this step quite a bit; also available via Package Control.

      But overall it has improved my CSS dev time a bit. Still working out the kinks as with any workflow modification, but I’m pretty satisfied with it :)

    • Permalink to comment#

      Great points. But I’m a web designer, not developer, and I still mighty prefer SCSS over CSS even after only having used it for a year.
      As for a text editor, chech out Sublime Text 2- very useful text editor with built in filebrowser- for OSXand PC. (On the subject of pp and software, check out Fire.app. Brilliant compiler.)

    • Anthony Delorie
      Permalink to comment#

      @Ricardo

      One day you might get a gig that requires over 6000 lines of CSS, to support selectors to show every sports team [including major colleges] logos in various sizes, sometimes a reference to an image [one logo] and sometimes to a large sprite, with it’s position. That’s a lot of redundant CSS to write, that’s a lot of sprites to generate. and nightmare to manage as teams change their logos, and teams come and go out of conferences. etc… when you can do that in less than a couple hundred lines of code, including generating the sprites with compass, and it actually be more readable in condensed form than searching a really large css file, I can’t tell you how invaluable that skill is, you have to experience it to appreciate it.

      It’s not that that complicated, but very powerful, you just need the right use case.

    • Permalink to comment#

      Ricardo – I’m a front end developer who has very little experience in js or php until recently but I happen to love sass. If you spend an hour or two watching some tutorials I can’t imagine you wouldn’t grasp it and want to use it in ur future projects. I wouldn’t even consider starting a project without it now, and not having features like nesting, extending, mixins, css3 vendor prefixes, percentages, variables and soooo much more. CSS just isn’t an efficient enough language.

      http://www.alistapart.com/articles/getting-started-with-sass/

      http://sass-lang.com/

      https://tutsplus.com/course/maintainable-css-with-sass/

  3. Richard Ayotte
    Permalink to comment#

    Another reason that I use LESS is Dojo. It’s their default preprocessor and most of my projects depend on Dojo.

  4. Permalink to comment#

    Using sass or scss as a “live” preprocessor is quite straightforward too – you don’t need to be using Rails, you just need Ruby & SASS installed on your server, and a compile hook in your framework. The python webassets package, for example, comes with a SASS preprocessor as a built in option.

  5. Permalink to comment#

    Hmm I agree with Chris. LESS is nice, but for SASS there’re so many more options. And SASS works great with Ruby on Rails too.

  6. So far I’ve been too set in my ways to consider using a CSS preprocessor. Anyone know a good article to use square one?

  7. What I like with LESS is that it’s so simple to implement, just add a Javascript OR use WP LESS if you are using WordPress. That plugin compile on the server side every time you reload the page when logged in.

    I hav’nt even tried the SASS yet because it seems like alot of work.

  8. Permalink to comment#

    I already had a PHP script to combine and minify my stylesheets (and one for my JavaScript), so adding the LESS processor to that existing script was really simple. I don’t use many features of LESS – but I do have my colour scheme defined up front so I don’t have to search and replace and I plan to use more features than I currently do (I was about to use them, but ditched rounded corners and gradients!)

    Search and replace seems easy enough, until you have a conflict.

    i.e. you have

    color: #336699; background-color: #FFF;
    

    and you need to update it to

    color: #FFF; background-color: #000;
    

    If you do it in the wrong order you mess a lot up.

    Equally, you have to be reasonably clever if you are replacing a shorthand like #FFF, as if you don’t find/replace using the terminating semi-colon, you may adjust other colours (#FFF5CC could become #0005CC).

    Plus you might want not want to replace all instances – so your find and replace gets ever more complicated.

  9. Permalink to comment#

    To Ryan above. Get started by:

    Download LiveReload
    Get LiveReload to comple less > css automatically on save.
    Start writing less.

    The beauty with less is that you already really know how to use it:

    https://gist.github.com/3761074

    Just start with some basic nesting, then move all of your colours to variables, and by then you’ll be hooked!

    Once you get hooked, you’ll NEED to look at less elements: http://lesselements.com/

    Imagine giving an element rounded corners by writing this:

    .rounded(15px);

    Instead of this:

    -webkit-border-radius: 15px;

    -moz-border-radius: 15px;

    border-radius: 15px;

  10. I am also using SASS instead of LESS.
    And yes I am more of a developer than designer :)

    But using SASS on Mac is easy as is on Windows.
    All you need to do is write inside your .SCSS and it compiles directly to clean .CSS

    WIN: http://compass.handlino.com/
    MAC: http://incident57.com/codekit/

    Has UI to control so good for designers too :)

  11. Thanks Dear Chris Coyier.

  12. rhurling
    Permalink to comment#

    Hmm, now this is kind of funny.
    I used exactly the same approach for a project of mine (about 7-8 weeks ago), where the users could decide what colors they would want for their site while the layout would be the same across all of the sites.

  13. Permalink to comment#

    I guess I’ve been dragged kicking & screaming to the LESS table. Oh well, time to see what all the fuss is about. I’ve never used any preprocessing. I like the idea, but my designer brain always reels at new scripty-techs. I have been using Pagelines since their early days and I really like it as a simple base for sites that don’t need to be completely custom. It’s good seeing Andrew here on CSS-Tricks. Please have him back again!

  14. Permalink to comment#

    I’ve been wanting the company i’ve worked at for the past 4 years to implement Server Side LESS or SASS preprocessing for a while now. The other guys here claim they only know CSS, but they are programmers (coldfusion) and would understand LESS and SASS in a snap. We don’t deal with PHP here, only ColdFusion, so perhaps I need to find someone that could make a port of LESS or SASS for CF to be ran on the servers here.

    I use SCSS (because of syntax highlighting, instead of SASS which i prefer) with Coda 2, for development only, and Jade for my markup, it’s a pretty sweet combo.

    My first preprocessor experience was when LESS first came out, and I loved it, even made a grid based off of it. Then I learned of SASS & Compass, the amount of pre-defined mixins made it the choice for me.

    BADA55 work there Andrew!

  15. Jox
    Permalink to comment#

    Well, first I’m started with LESS too — it’s so much better then plain CSS. But then I tried SASS/SCSS and fall in love with it. Plus, Compass is really cool.

    BTW, here is good site with Compass reference — found it yesterday.

  16. Nate
    Permalink to comment#

    I’m more of a designer-type, but one of my programmers got me using SASS and I love it. I convinced our server admin to include SASS hooks in our svn commit sequence, so we use SCSS for our large projects.

    I opted for SCSS because I could use all of our previous CSS as written (just change the extension), and add the cool SCSS stuff to files as needed. It also kept things comfortable for those who didn’t write much CSS and didn’t want to learn SASS—they could just write CSS.

    For my local development, I use Codekit, and for my recent projects I’m actually using both SCSS (for most things) and LESS (for Twitter Bootstrap) at the same time, since Codekit lets you do that. I develop mostly in Coda (because of their awesome code completion); the SASS/SCSS mode is built in.

  17. Permalink to comment#

    In order to use the LESS CSS syntax, another solution is to use a LESS CSS compiler as Less Now.

  18. Permalink to comment#

    Take a look at new css tool http://html.adobe.com/webstandards/csscustomfilters/cssfilterlab/ created by Adobe, for discovering CSS Filters & CSS Custom Filters.It allows us to apply any number of filters from a list, customize their values, see the output instantly and get the CSS rules generated.

  19. Permalink to comment#

    Thanks for informative article, this shows more valuable information than the documentation.

  20. Permalink to comment#

    When you start using CSS Preprocessor, there is no way to go back to plain CSS.

    Personally I still prefer LESS to the others. Mainly becuase that’s the one I feel most comfortable with.

  21. Permalink to comment#

    I now know how to create a new wordpress themes look into various colors thank you, this post simple and easily understood by beginners like me

  22. Allen
    Permalink to comment#

    Designer; I use LESS which I find great, once got head around it. Love writing .boxShadowMe(10) once the class is setup!

    I use Drupal 7 and there is a great LESS preprocessor module for that. With D7 on localhost my workflow is the same as it’s been since 1997 – save file, refresh browser, repeat.

    Once you’re in production mode you switch on LESS caching and it uses the last CSS file it wrote for no speed implications.

  23. Bob
    Permalink to comment#

    Great article, thanks.

    I’m interested in the part of the process missing from this article, where you include individual variables such as colour, entered via a php web form. How do you accomplish this? i’ve seen .css.php before but it seems such a nasty hack, I’m curious how you modify your less file variables from PHP. Do you string replace the variables in the less file before you compile, or do you generate the variables.less file completely in php each time you rebuild?

    Thanks in advance,

    Luke

  24. I made a plugin which can edit Less variables live on any page. Not free but hope you will like it:

    http://www.virtuosoft.eu/tools/live-less-theme-customizer/

    Any suggestions are very welcome!

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".