Quick Tip: You Need to Check out LESS.js
videos

Quick Tip: You Need to Check out LESS.js

Tutorial Details
  • Topic: Faster CSS
  • Technology: JavaScript
  • Estimated Completion Time: 4 Minutes

You might be familiar with such services as LESS and Sass. They allow for far more flexibility when creating your stylesheets, including the use of variables, operators, mix-ins, even nested selectors. However, because LESS was originally built with Ruby, a lot of PHP developers, despite the fact that there are PHP versions available, never used it.

That’s all going to change now that LESS is being rewritten in JavaScript, is about forty times faster than the Ruby version, and can be used by any of us!


Step 1. Reference LESS.js

<script src="http://lesscss.googlecode.com/files/less-1.0.18.min.js"></script>

Step 2. Import a Stylesheet

<link rel="stylesheet/less" href="style.less" />

Note that we’ve set the rel attribute to “stylesheet/less,” and that our actual stylesheets has an extension of .less, not .css. Also, we must link to this stylesheet before Less.js.


Step 3. Have Fun!

With this minimal amount of work, you now have access to everything from variables to mix-ins. Be sure to watch the four minute video tutorial above for full examples, but here are a few quickies.

/*
Variables!
*/
@primary_color: green;

/* 
Mix-ins are like functions for commonly used operations,
such as apply borders. We create variables by prepending
the @ symbol. 
*/
.rounded(@radius: 5px) {
	-moz-border-radius: @radius;
	-webkit-border-radius: @radius;
	border-radius: @radius;		
}

#container {
/* References the variable we created above. */
	background: @primary_color;
        
/* Calls the .rounded mix-in (function) that we created, and overrides the default value. */
	.rounded(20px); 
	
/* Nested selectors inherit their parent's selector as well. This allows for shorter code. */
	a {
		color: red;
	}
}

It’s important to remember that LESS.js isn’t finished; hopefully, it will be soon. Nonetheless, it’s working wonderfully so far. What do you think?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.daniel-petrie.com Daniel Petrie

    That’s pretty neat and useful. The only thing I would be concerned about is having styles dependent on having javascript enabled. But I guess if it is just “enhancements” rather than the page layout itself it shouldn’t really be an issue.

    • http://net.tutsplus.com Jeffrey Way

      Or, just use this during development.

      • http://webitect.net/ Nick Parsons

        Definitely an awesome tool – thanks for the screencast! I’m quite amazed :)

        You mentioned using it for development to avoid js dependent styles – is there a tool that can take a .less file and output production ready css? If there is, it would make sense to use it for development (and gain the speed) and then still be able to have non-js dependent styles when you’re finished. If you’d have to translate your development less styles over to css manually though, I don’t think using less.js for development would be that useful.

      • http://kory.gorsky.ca Kory Gorsky

        This is so boss.

        Love the idea of using this during dev only.

      • Peter

        @Nick Parsons: Yes there is such a tool… LESS!

      • http://webitect.net Nick Parsons

        Yes, obviously :) But I thought the point was to get away from having to install and run a server-side framework.

      • http://onlineqrlab.com qr

        Same question as Nick. The less.org website seems to be focusing on Ruby only.

      • simon

        @Nick Parsons: No need for server-side stuff, just put ruby on your dev system and generate the css there before pushing it to the live server.

    • http://cloudica.net/ Sam

      Easy fix, try making another .css stylesheet with the LESS features removed, and call it in noscript tags.

    • John

      @Daniel: you have to STOP thinking about people have their javascript turned off.. If he is one of those 0.001% who have it turned off, then they are aware of the results they are getting.

      • http://mediagearhead.com Giles

        @John Game Set Match

      • Rich

        @John: I don’t think that argument makes sense, there should be a clear separation of content(HTML), functionality(Javascript), and presentation(CSS). Adding dependencies between these layers is always a bad idea. There would also be a huge performance hit ‘compiling’ CSS at run-time.

        However, I assume it isn’t intended to be used this way. Surely the point is to either serve the files from Ruby or Node as compiled CSS, or compile the LESS files during development and use the outputted CSS in production. To me the former makes much more sense, but I suppose the client-side option is there for people not familiar with Ruby or Node.

  • http://www.gradientgraphics.net Wes D

    Nice! I actually hadn’t heard of this yet and I think I’m in love! Thanks for the tip Jeff!

  • http://davidfitzgibbon.com David Fitzgibbon

    That sounds class but what happens if the user has JavaScript turned off? Does it break the design?

    • http://mario.ec/ Mario

      This is another good reason for not using Less.js on the client side.

    • w1sh

      As JW mentioned above, just use this while developing, then you can view the page’s generated CSS -> Copy/Paste to your own style.css.

  • http://mario.ec/ Mario

    As innovative as Less.js is I still think this kind of processing should be done server side, it is only run one time on the server, per version, and you save a blocking call. I know it caches the results locally in modern browsers, but still I think Javascript should be used for interaction and not for CSS processing.

    • http://davekingsnorth.com Dave Kingsnorth

      Once again, your missing the point a little bit. The page source is rendered as normal CSS, after development you can copy and paste the source code and omit the javascript

      • http://davekingsnorth.com Dave Kingsnorth

        Actually it was me who missed the point of your comment a bit, sorry. I just don’t really get why it makes a difference how you process it? To me this was an open shut case on how you would use less.js to make development quicker and perhaps some of the finer issues have gone over my head.

  • http://sirestudios.com Tommy M.

    Holy crap. This is how CSS should have been formatted in the beginning. Amazing.

    • Jota Carlos

      I tottaly agree.

  • http://shoxty.com Will

    Ive been using SASS for a long time now and it basically changed my life when it comes to CSS. I’m very excited about LESS.js and will definitely give it a try. Great find!

  • http://www.johnwooten.info drumkeyjw

    Thanks! Interesting…yeah, same concern with Javascript being turned off…but very neat!

  • http://envexlabs.com Matt Vickers

    I’ve been paying attention to LESS for ruby while I’m trying to learn ruby & rails, but I’ve got mixed feelings about this.

    The developer in my loves it, and it seems like the greatest things since sliced bread, but on the other had it kinda screws over any clients I use it for.

    Let’s say a few years down the road they want to update their site and I’m not around. Unless they can find a developer who knows about LESS and how to use it, they may be a bit lost.

    It’s a double edged sword, but so are most web technologies :D

    • simon

      Well, those new developers can do their magic on the less-generated css, your client never even has to know you used it on your dev. system … it’s just like using an WYSIWYG editor to create an HTML file, that doesn’t stop any other developer from using Notepad to edit that same file …

  • http://danharper.me Dan Harper

    I think LESS is a brilliant idea, but it shouldn’t be done through JavaScript. I’m going to try out the Ruby gem version for the development of my next project, and use it to compile CSS files which I’ll use production side as this really is the way CSS -should- be.

    But the ‘live development’ feature of LESS.js looks great (it will automatically update the CSS on the page when you update the file, without refreshing).

  • http://twitter.com/catshirt catshirt

    what is the benefit of running this on the client as opposed to precompiling on the server? regardless of suggested speed, it is still unnecessary heavy lifting on what is still a fragile platform.

    likewise, javascript implementations of sass have existed for quite some time. maybe I’m missing something, not really seeing the big deal.

  • http://jacobdubail.com Jacob

    Wow. That is too cool. I already add a commented section to the top of my css with all of my colors. That way, if I ever change one, I can do a find/replace on my entire stylesheet. This take it one step further… well, maybe 4 or 5 steps further.

    Thanks for introducing this!

    • http://jamiebarrow.deviantart.com James Barrow

      Variables are definitely a much needed thing in CSS

  • http://www.marioawad.com Mario Awad

    Great screencast. Thank you.
    However, I don’t like relying on the availability of JavaScript and I’m interested in the PHP version of LESS, can anyone point me in the right direction? Cheers.

    • w1sh

      You’re right. It would be a pain to copy/paste the .js version of it, so if you’re into PHP:
      http://leafo.net/lessphp/

      There is also a Drupal module for LESS that runs on the same preprocessor:
      http://drupal.org/project/less

      • w1sh

        LessPHP is super easy to implement.

        1) Go to the above mentioned link.
        2) Download the stable tar.gz.
        3) Put that first quickstart code in there (and make sure it’s pointing to the right directories/files).
        4) Blamo!

    • buritica

      Jeffery did a premium tutorial on a really good tool called Scaffold CSS (http://net.tutsplus.com/tutorials/html-css-techniques/this-will-change-the-way-you-code-your-css-new-plus-tutorial/) it is very similar, but it is php based, it is parsed by the server, (although less can be used in the server as well with node.js), and has many many mixins and cool tools. Like generating gradient images from your css and using flags to change colors and variables based on the time of the day of month. have a look.

  • w1sh

    I’d just like to point out that JW stalks me and it’s getting annoying.

    Every thing I begin to study he comes out with a “Quick Tip” on that completely makes the past 2 days of trudging through doc a complete waste of time.

    Anyway, if anyone wants my 2 cents from these past few days, there are several of these preprocessors:

    HAML and SASS are the 2 big ones. HAML is almost overwhelming with the amount of crap they stuff into it, but if you learn it, I bet it’s good. HAML also seems to work really well with Ruby on Rails, so if you’re into that kinda stuff…….
    HAML sucks because it doesn’t have a built-in “watch” function that updates your .html when you save your .haml. You have to go through some crap called StaticMatic and it’s just a pain in the ass. Screw HAML. Use SHPAML instead. It doesn’t have a “watcher” either, but it’s a lot less overwhelming.

    SASS is pretty awesome. It’s a slightly more elaborate (complicated) version of LESS, but it also has a lot of features LESS doesn’t. Like full CSS3 support (LESS has yet to embrace the “filter” property…. ugh…).

    Compass seems like it’s just a collection of other people’s work that runs behind SASS. It allows for you to import CSS frameworks and use them easily; give their classes whatever names make sense for you (grid_2 becomes sidebar); and um… I don’t know. I’m sure Chris Eppstein will chime in here in a second and get all sassy because of all the hard work he put into it, but it seems like it’s just a lazy way to import CSS frameworks.

    Anyway, I suppose my two suggestions would be SHPAML (or just straight HTML) and SASS (just because of it’s full CSS3 support).

    LESS and SHPAML have the best syntax and stuff though. I like them a lot.

    • w1sh

      Oh, and… MOAR PYTHON/Framework TUTS!!!!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      haha

  • Paulo Vítor

    Very impressive!!!

    Alô Brasil!!!!!

  • http://www.venture-ware.com/kevin/ Kevin Jensen

    Awesome stuff as always. I will definitely start using this.

  • http://www.xboxgamertag.com Gamertag

    Thanks for the tutorial, just wondering why your always rushing them on video?

    • http://envexlabs.com Matt Vickers

      I think it’s because he started them on screenr which is limited to 5 mins.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      For two reasons. 1) To cram as much as possible into 4-5 minutes. If it goes past 10, people stop watching. 2) Screenr.com limits videos to 5 minutes.

      • Chris

        How about putting the videos back on iTunes?

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Hey Chris – We could. We still put the full tutorials on iTunes. But, we don’t currently have an easy system to do so for the YouTube videos as well. But yeah, that’s something I’m working on. :)

      • bootdisk

        Actually, if it’s a video, I’m not even watching.

        I mean, why do you have to provide so much of your content as videos ? I usually can’t listen to the sound at work, and when I’m home, I don’t like having to sit and watch something I’d rather read. Even if you are “rushing”, I’m willing to bet that I can read a text faster than you read it aloud. And a text version allows me to visually “scan” the page for the interesting parts. I really hate this tendency to go full-video on the web just “because you can”.

        The web is not television, nor should it try to look & feel like television.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        That’s perfectly fine if you don’t like screencasts. We have hundreds upon hundreds of written articles as well. These are for those who prefer the video format — and there are many of them. To each his own. :)

      • bootdisk

        …and this is why I’m still reading tutsplus. If you only had screencasts, I wouldn’t even be here in the first place ;)

        Moreover this article is perfectly understandable without watching the video, so I guess it wasn’t a good example – but I really had to say this, somewhere :)

  • Markus

    Hey Guys

    I just wanted to throw in another aspect. Especially if you work on a linux os you’ll have ruby gems preinstalled. Now using SASS with its –watch parameter you can work in real time, as if you wrote normal css. It updates the css from the scss file every time you save it. So THIS is pretty cool ;).

    My workflow is now just getting optimized through ZEN-Coding and SASS and so i gained SOO much time, which i can use to think about what i need to write and not waste all this time typing this brackets and stuff. It’s just fun.

  • http://www.mcmillangraphics.com Michael McMillan

    Thanks for the tip! Very useful.

  • drumkeyjw

    Does anyone know where I can find the latest Javascript stats as far as who has Javascript turned off?

    • http://thadknowsweb.com Thad Bloom
    • buritica

      Don’t guide yourself by those statistics. Those are gathered only from users who access w3schools. this site is mainly accessed by designers and developers, who tend to have the latest versions of each browser. Have a look at https://netaverages.adobe.com/en-us/index.html as well. Stats usually depend on your site’s target audience.. for this you can use google analytics and see which browsers apply to your situation.

  • Andreas Madsen

    Nice script but:
    Where do i find the source file?
    I can only find the compressed file.

  • http://dagrevis.net/ daGrevis

    Looks great, but let see later… =)

  • http://designfortress.com dreame4

    It’s pretty amazing thing but only when you use it in development. However, making fully featured CSS files from .less file shouldn’t be difficult.

    I’ll try it in next week as I’m going to build base under my next project.

    Thanks for tutorial! ;)

  • Ivo Trompert

    Nice, but not for in production.

    There is a PHP alternative, it’s name is CSScaffold and can be found on github:

    http://github.com/sunny/csscaffold

    • http://812studio.com benjamin

      Ivo, thanks for mentioning Csscaffold. I was hoping this would come up in the discussion.

      After using CSScaffold for the past 6 months, I can’t see the benefit of using LESS.js. LESS just seems like a very slim version of CSScaffold.

      Here’s one useful example, you can write easy-to-read long hand CSS and then easily configure CSScaffold to minify your CSS before output. On the dev end you code stays easy to read. On the client side, the code is optimized and fast to load.

      Although LESS seems like a simple and quick way to start cranking out CSS, it lacks tons of features that CSScaffold provides.

      • http://812studio.com benjamin

        And CSScaffold works like a dream in WordPress!

    • http://danstondin.com Daniel Stondin

      Does anyone know what has happened to Anthony Short’s original repo? There’s no longer a wiki or a git repo by the looks of things? Just interested, as I’ve enjoyed using Scaffold recently.

    • http://danstondin.com Daniel Stondin

      Quick question about CSScaffold… Has anyone had issues with the processing time of the Server side PHP? I often get a delay on my web pages where the page looks like no style-sheet exists, and a few seconds later the CSS kicks in. Just wondered if anyone else had had a similar issue.

      • Ivo Trompert

        I don’t have got those problems. The problem I ‘m getting is if I use the @font-face option of CSS. When I use that I get a page not found error.

      • http://www.aediscreative.com Christopher Uryga

        Have you been able to figure out the @font-face error yet?

  • http://www.acrylicstudios.com/en/ timeNomad

    Damn this is such a time-saver!
    Totally digging the mix-ins, can think of plenty of practical uses for it; per-browser declarations for fancy CSS3 attributes… and well that’s all I can think of right now but sure there’s more!

  • http://matt-bridges.com/ Matt Bridges

    Oh, my….can’t….breathe….so…..AMAZING!!!!!!!!!!!! This is absolutely awesome! Great tip on this Jeff. Definitely looking forward to using this in my future projects.

  • Michael

    Hi Jeff, nice tut as always!

    I’m wondering how you did the spacing in your DOCK. It looks like grouping some items, but how can i do this?

    regards, michael

  • Chris

    Thx for this jeff! I love this.

  • Rinaldo

    Awesome quick tip

  • http://dazydude.net Rik de Vos

    Thanks Jeff! That’s awesome!

    If I had known about this a few weeks earlier, my life would have been a lot easier

    Cheers,
    Rik de Vos

  • http://www.pokerbanda.com Andrew

    Hmmm…

    To use this you have to reorganize all your development habits regarding css and layout testing. Thanks for effort of informing us on LESS, but i don’t see this technique coming in my work-flow anytime soon.

  • Brad

    This is absolutely awesome. Color me a convert. I could have used this today

  • Hydraulics

    I think its fantastic.

    Your template can change with the seasons maybe.

    I would love to see an easier way for your members to interact with the site a little more. They could change the template depending what mood one is in :)

  • http://wildanr05.student.ipb.ac.id wildanr05

    forty times faster??? It’s definitly worth a try! Thx for sharing

  • Denis Molan

    This is very useful stuff not only for development even for web page when public. LESS name suits the script :D LESS work MORE time :D.

    Every one are woried about client-side, what about jQuery which is too client side and new modern pages has mostly jQuery implemented + by defult browser javascript is ON, so i would say 80+ % has javascript ON.

    I think if LESS will do their job good its community and script usage will grow, hopefully same as jQuery one ;)

    I think i will test this out soon :D, i tracked it has little problems with IE browsers so don’t forget test with ietester ;)

  • http://kimhallberg.se/ Kim

    Cool stuff, that’s going to do things really easy, like that.
    Well, I’m gonna go a bit off-topic here and ask you Jeff if you did post that tutorial on the shortcuts you use on you programs, ” beginhtml ” I think you had on one, would love to see that, hope you shared it, if you didn’t would love a tutorial on that, if it works on windows of course, anyway, hope you give a shoutout of some sort if you got a tutorial or not. :)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Hey Kim — I use TextExpander for that. But I’m asked this question often. I’ll try to try record a quick video tip next week on the various tools like that.

      • Ilias

        Maybe you could also give away the theme you’re using for Coda?

        It looks like a copy of ideFingers (for Textmate).

        http://idlefingers.co.uk/

      • Ilias

        ..give away “the name” of the theme..

  • http://www.cbesslabs.com Bratu Sebastian

    Nice tip. I would give it a try, but I know something:

    Every time we add another tool into our development framework, it makes our work harder.

    If you have been slicing and writing css from scratch for 4 years now, this tool would help you, otherwise, you would have to work more.
    I would categorize these technologies by the status of the developer ( professional / entry-level ), so we don’t have a beginner mess all up with a new technology he doesn’t yet knows well.

    And more Youtube videos !

  • http://www.xcellence-it.com/ Xcellence IT

    Hey, its awesome.. but how to use this ? Is there any Getting Started tutorial for using this? Moreover, on its website, there is no mention of Less.js, it was asking for ruby on rails?

    Any good documentation will surely help.

    • http://net.tutsplus.com Jeffrey Way

      Did you watch my video tutorial? That shows how to get started from scratch.

  • http://www.xcellence-it.com/ Xcellence IT

    can we use it with WordPress ?

  • http://www.jordanwalker.net Jordan Walker

    Thanks for the heads up, it seems like everything is moving in the JavaScript direction. Who knows, one day all HTML and CSS will be generated by JS?

  • http://www.xcellence-it.com Xcellence-IT

    Hi,

    It works well with wordpress too., the only issue in using LESS with wordpress is that, we need to specify absolute urls of all the images in CSS. Otherwise, it works well.

    Thanks for such a great tool.

    Thanks
    Krunal
    Xcellence-IT

  • http://www.mfx.ro marius

    JavaScript isn’t a big problem! So, why Google maps use it to render maps???
    JavaScript is disabled on ~8,5% of visitors browsers in entire world. If you have some mashups in your site, you think at users with javascript disabled? I guess no.

    According to http://visualrevenue.com/blog/2007/08/eu-and-us-javascript-disabled-index.html, data collected in 2007, 1.04% have it disabled in the EU, and 3.05% have it disabled in the US.

    The problem is more apparent on mobile browsers, but we will likely serve different content to them anyway,

  • Vin

    Looks amazing, but for the life of me, couldn’t get it to work following this tut!

    .htm
    ——

    {less}

    Bueller… Bueller… Bueller…

    style.less
    ————
    @primary_color: red;

    #container {
    width: 200px;
    height: 200px;
    background: @primary_color;
    }

    • Vin

      Erm, obviously can’t post html in here, but I was using the same html more or less as in the video. Anyone else not get it working? Pointers??

      • Brad

        Wouldn’t work for me either after watching the tut. I used the same code as the tut and made a separate complete page. Nada. I’m hoping its just google messing with us.

    • Joel

      Your syntax is fine. Make sure the link to your stylesheet comes before the link to the script.

  • http://aniwood.org Ryu

    Wow! quite nice!

    When i think about it the that almost any browser can natively use JS, this wold be awesome if less would be some kind of css++ natively supported by browser implementations. Opensource and integrateable.. would be a nice to see when every developer could use LESS-style css coding in any page with native browser-side-processing ;)

  • http://blog.larsjung.de Lars

    Interesting article. Exactly what I am looking for. Had some experiences with Scaffold, but this here looks very nice! Will give it a try right now.

  • http://www.jc-designs.net/blog Jeremy Carlson

    Ok fine! I’ll look at it. I have started using Sass 3 recently, and I freakin love it. I’m always into trying and learning new things, so I’ll watch the video of this tonight. Real quick though, I assume this plays nicely with other libraries? Specifically Ext. and jQuery?

  • Joel

    It’s very nice to see less come to the javascript world but I think CSScaffold is really where it’s at. It just makes more sense, to me anyway, to use PHP to do this sort of thing. Plus you can actually see how the source code is being rendered with less.js you can’t.

    One nice thing I can say about less.js is the error reporting is very slick. But I think they have a very long way to go.

  • Julius

    Less is amazing and I can use it for selected projects because the product is dependent in javascript. The problem here is we still have to consider some people (note: user that will benefit from your website) turning their javascript to off.

  • http://spotdex.com Davidmoreen

    Would this not cause massive problems for users in the stone age, with javascript off? Also, no syntax highlighting, is just the worst!

    • http://67ideas.com Jack Hoge

      Good point, David. Maybe just have a barebones stylesheet (like a slightly enhanced CSS reset) for users without JS? At some point you gotta draw the line between accommodating users and preserving your sanity, right? :-)

  • Greg McAusland

    This does seem like quite a brilliant time saver, especially for many of us who have come from programming and had reusable structures drilled into our heads from day one. It’s almost how CSS should always have been rendered.

    But unfortunately it isn’t and despite how useful it would be in development I still feel that enabling another layer of dependance isn’t a good thing. I don’t care so much about js statistics these days, we have to realistically push forward to achieve any kind of decent web functionality. However, abstracting something as core as CSS writing worries me, for multiple reasons.

    I don’t see it as a good thing to become reliant on shorthand coding methods which ultimately will slow the rendering of your page in a world where every millisecond saved is like gold dust.

    The only deployment I can see is locally, during development. Then there is the added headache of having to recompile your CSS file each revision before upload.

    Is the added formatting, readability and ultimately a method of killing forking for multiple browser css3 support worth the extra effort ? It might well be, I think trial and error could answer that question. Imagine if you could develop a coda extension to compile the less to CSS on publish to the server… Now that would be a game changer. I’m still weary about abstracting myself from native CSS but if I could become inline with my current tools I doubt I could refuse it’s advantages..

    Regardless, I’ll give it a whirl on a local environment. (god, long comments ftl)

    • Greg McAusland

      So half way through hacking up a coda plugin to compile LESS files I came across the game-changer which someone has already done, and done extremely well.

      http://incident57.com/less/

      if you want to use Less seamlessly locally with automated CSS spit-out you NEED to check this out.

  • http://fishmemory.net frctalbit

    Am i the only one who noticed it does not work on ie8 in compatibility mode? So i suppose it does not work in IE 6 and IE 7.

    Also, i did not find an easy way to get the final pure css the less library produces :( (View source still points to the .less file)