Using LESS with WordPress

Back when I used to have an office job, 80% of the work was repetitive and far from challenging. As a result, I came up with ways to automate various tasks (think Excel Macros, Access, Crystal Reports, etc.). This allowed me to focus on items that actually required some form of judgement or decision-making. When I made the leap to the web industry more permanent, I found myself facing the same mundane work. Vendor prefixes became the new TPS reports. In the process, LESS (or SASS) became my new macros. In this article, I’ll show you how you can also drastically increase your productivity and focus on what matters.

Preface – Still using CSS?

LESS allows you to use a syntax style that naturally extends CSS in ways that can drastically optimize your workflow. If you’re a web designer and aren’t using one, you’re probably spending more hours on client projects then you really need too.

There are also a number of people who hold onto writing CSS for reasons of purity, making preprocessors sound as evil as growth hormones given to animals. Truth be told, there’s nothing sexy about having 10,000 lines of static CSS. Besides, CSS zen doesn’t come from indenting vendor prefixes in a straight line, but finding the right balance with regards to specificity and flow. I feel as we sometimes focus on too many of the small details as opposed to the big picture, which is why we often see alphabetically sorted properties but nothing that resembles an effective table of contents (nothing against the former, but the latter takes precedence).

At the end of the day, once your files are minified, concatenated and stripped of any comments…  we’re all equal. Ready to get started?

1) Setup LESS

The most seamless experience you’ll have using WordPress and LESS is by using wp-less, which acts as bridge between WordPress and less-php (a general PHP compiler for LESS). There are other ways to implement LESS (less.js, node or pre-compiling via a desktop application). I just find the on-the-fly compiling to be the most painless solution for small to mid-sized websites. It compiles only when any of the original LESS files are changed (including anything brought in via @import), so the outputted data will always be the compiled CSS.

To install it, you can either include my front-end starter foundation (more information on that in the next section) or submodule the repository directly and pull it in through your functions.php, like so :

require_once( 'wp-less/wp-less.php' );

To use it, simply enqueue a LESS stylesheet the same way you would CSS. The difference is wp-less runs a filter and checks for any mention of the “.less” extension thus diverting it’s path to the compiler before outputting in the header of your document.

wp_enqueue_style( 'less-style', get_stylesheet_directory_uri() . '/style.less' );

That wasn’t so hard was it?

2) LESS Structure

Like many developers out there, I have my own foundation I use for projects (it includes a template that outputs theme styles like this). I’ve finally taken the time to consolidate it as a github repository so that others can use it if they wish. It’s called prometheus and is my starting point with regards to any front-end development on WordPress. It contains my base LESS files, wp-less, WPThumb (a superior thumbnail solution for theme developers) and the styles template.

As all the LESS data is compiled to a single CSS file, it’s very easy to keep a modular structure that allows for a “table of contents” view through multiple files, folders and prefixing.

You’ll notice on this website that I enqueue two files, screen.less and print.less for their respective purposes. However, print.less is simply a different collection of modular pieces then screen.less is.

functions.php


function nt_less() {

     if ( ! is_admin() ) {
          wp_enqueue_style( 'screen', get_stylesheet_directory_uri() . '/screen.less', null, '2.2', 'screen' );
          wp_enqueue_style( 'print', get_stylesheet_directory_uri() . '/print.less', null, '2.2', 'print' );
     }

}

add_action('wp_enqueue_scripts', 'nt_less');

screen.less

/* Foundation
* ----------------------------------------------------------------- */

@import "prometheus/prometheus.less";
@import "prometheus/less/1140.less";

/* Site
* ----------------------------------------------------------------- */

@import "less/variables.less";
@import "less/typography.less";
@import "less/body.less";
@import "less/mobile.less";

/* Plugins
* ----------------------------------------------------------------- */

@import "less/x_jquery_grid.less";
@import "less/x_wppaginate.less";
@import "less/x_gravityforms.less";
@import "less/x_syntaxhighlighter.less"

print.less

This took another five minutes to put together due to the modular structure (try print preview to see the end result). It’s a stripped down version of screen.less with the added .do-not-print class.

/* Foundation
* ----------------------------------------------------------------- */

@import "prometheus/prometheus.less";
@import "prometheus/less/1140.less";

/* Site
* ----------------------------------------------------------------- */

@import "less/variables.less";
@import "less/typography.less";

/* Print-specific
* ----------------------------------------------------------------- */

.do-not-print {
    display:none;
}

3) LESS Tips

Now that you’re setup with LESS and WordPress, you’re ready to save some serious work time! There are a number of common practices I’ve come up with that I hope will help you out too:

Create duplicate LESS files for your Plugins

You’ll notice in screen.less I have separate LESS files for the plugins I use on this site (all prefixed with “x_” so that they sink to the bottom of my directories). I always turn off plugin styles and copy the contents into a LESS file. This allows me to use variables and mixins right from the start when it comes to customizing their individual styles. It’s a pain to have to edit vendor prefixes within other CSS files or to constantly have be wary of any plugin updates overwriting your files.  Plugin CSS rarely changes in my experience and having them in LESS right from the start is a huge win (and results in less files being outputted, no pun).

Generic and Prefixed Variable Names

During the construction of a website, you’ll easily find yourself changing colors and fonts regularly till you find the right fit. Whilst I used to use variables such as @helvetica or @lightblue, I now use more flexible equivalents, such as @f-body and @c-hover. This comes with the great benefit that you never have to change the variable names across different files, nor do you ever have to wonder what the context is.

Nesting is your friend

This is one of the features I find so powerful yet underused with LESS. Nesting gives us an enhanced workflow for inheritance, one that effectively kills off repetition and provides truly valuable visual structure.

Let’s take a simple example. Check out the responsive version of this website and you’ll notice a navigation toggle. The LESS for this is dead simple, and probably doesn’t feel too remote from standard CSS. However, imagine this with multiple dropdown’s, interaction states and more. Being able to nest in such situations is invaluable (anyone remember superfish.css? ugh, endless .sf-menu declarations).


#mobile-nav-flyout {

   background:rgba(18,38,60,1);

   ul, li {
      margin: 0;
   }

   li {
      text-transform: uppercase;
      font-size:16px;
      border-top: 1px solid rgba(255,255,255,0.05);
      border-bottom: 1px solid rgba(0,0,0,0.15);

         &:first-child {
            border-top:none;
         }
         &:last-child {
            border-bottom:none;
         }

         a {
            display:block;
            padding:10px 20px;
         }

   }

}

Easy Color Changes

Colors change so often during development that it can be time-consuming to constantly go and find the right hex colors.

Instead of having to seek out random hex colors such as this example:

.gradientBar(#FF5536, #ED3314);

We can simply work off a color variable to create a slightly lighter or darker value:

.gradientBar(@c-sec + #111, @c-sec);

Both will output the same in the end:

background-color: #f73d1e;
background-image: -moz-linear-gradient(top,#fe4425,#ed3314);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#fe4425),to(#ed3314));
background-image: -webkit-linear-gradient(top,#fe4425,#ed3314);
background-image: -o-linear-gradient(top,#fe4425,#ed3314);
background-image: linear-gradient(to bottom,#fe4425,#ed3314);

Do you use LESS?

What are your experiences with LESS? Are you using it for WordPress or client projects? Would be interesting to hear how others setup their themes and have increased their CSS productivity.

  • cehwitham

    Noel, great article. I’ve long seen the advantages of LESS but not found a way to integrate them into my WordPress workflow. This looks like a good way to make it easy to work with.

    Do you remove the themes standard style.css file, does the style.less overwrite it or do you end up with two main style files?

  • Dan

    Less is great I’d also recommend a simple mixin library like elements.less

  • http://twitter.com/no_fear_inc Mario Y. Peshev

    We’re using SASS, but not including the .sass files directly; compile them to plain CSS instead. The standard sass tool has a ‘watch’ param that syncs the sass file to the css file and updates it when any of the sass submodules has changed.

  • http://www.noeltock.com/ Noel

    Thanks for the kind comment!

    style.css and my LESS files are independent from each other. I simply do not enqueue/pull in style.css as it only contains the information to register the theme. See mine here: http://noeltock.com/wp-content/themes/nt12/style.css . So it’s necessary for WP, but not for actually displaying anything. Does that make sense?

  • http://www.noeltock.com/ Noel

    Yep, that’s a nice set of mixins to start off with. After a while, you’ll develop your own style which is why it’s prudent to host your own set of mixins (regardless if it’s a 1:1 copy or entirely your own material). I started out with the mixins from bootstrap and then started adding my owns one in.

  • http://www.noeltock.com/ Noel

    That is definitely the traditional web agency way (i.e. desktop compile). I’ve come to view the outputted CSS (from LESS or SASS) as a temporary file, which is why I’m quite comfortable treating it the same way as images and thumbnails (upload original, let server create/compile other variants).

  • http://twitter.com/mkjones Michael Kimb Jones

    Writes article about LESS.

    First comment is about Sass.

  • http://www.noeltock.com/ Noel

    Heh, they’re very similar so you could likely copy paste this article replacing everything with SASS.

  • http://remkusdevries.com/ Remkus

    How would you go about compiling it into the style.css file using this setup?

  • http://www.noeltock.com/ Noel

    Filter the output directory using this bit: https://gist.github.com/3826136 . You’d have to open up a few permissions on that dir I assume. Like said in another comment, outputted CSS to me is not much different then images sizes generated by WPThumb, so it all belongs in the cache imho.

  • http://remkusdevries.com/ Remkus

    Thanks for the spicy spicy reply ;)

  • http://twitter.com/saltcod Terry Sutton

    It’s really worth giving LiveReload a try. I find that it hardly ever gets mentioned, but it’s very, very good. All you need to do is:

    1. Add/drag your theme folder to LiveReload
    2. Duplicate your style.css file and call it style.less
    3. As you work in style.less and hit Save, it LiveReload will automatically compile it into style.css.

    This way, you’re not compiling on the fly and there’s no extra files to enqueue. And having css injection (no page refreshing) is HUGE for me. I can’t imagine working without LiveReload now.

  • http://www.noeltock.com/ Noel

    Sounds cool, plenty of these sort of live desktop compilers (even for free too which is great). I’m happy to stay with wp-less as the compiling is dead fast and only does it if a file has changed. There are however no additional enqueues in my example (except for print.less, which would in turn still have to be a print.css).

  • Foxinni

    Saaa-weeeet! Can’t code normal CSS anymore. Too laborious. Plus mixins… just to damn cool. Thanks for the share. Incredible work…

  • Rahe

    Less is very powerfull and sweet.
    For the theme there is a solution making a css static file, compress it and enqueue it :https://github.com/herewithme/less_theme_generator
    When there is a change on any less file, the compilation/compression is done again :).

  • http://case.oncle-tom.net Oncle Tom

    Hi! Nice article.

    There are a couple of plugins speeding up the dev, as the one you mentionned.
    Another one lives in the WP Plugins repo: http://wordpress.org/extend/plugins/wp-less/ (I am the author of this one).

    It already deals with cache busting, theme embedding, rebuild in debug mode and so on.

  • http://twitter.com/sanchothefat Robert O ‘Rourke

    You beat me to that repo URL! I always forget to check if someone else has written one first…

  • http://twitter.com/sanchothefat Robert O ‘Rourke

    There’s http://github.com/sanchothefat/wp-sass too but that hasn’t been as extensively tested. There’s also no nice way to send variables into the compiler that I know of yet. Need to check the latest version out.

  • http://twitter.com/mttorley mttorley

    awesome workflow- now i can drop my win-less compiler and run it IN WP. thanks for making the world faster!

  • Ro

    Really cool article. Only started using LESS in my projects in the past few months. Wouldn’t dream of going back!

  • http://danielgroves.net/ Daniel Groves

    Ah this will be fantastic at work where not all developers can easily compile the less on their local machines.

    Personally, I prefer to work on my local machine where possible so I just let CodeKit take care of everything int he background for me.

  • http://www.mydietarea.com/ Mydietarea

    Thats incredible…

  • Eduardo

    CREATE DUPLICATE LESS FILES FOR YOUR PLUGINS
    Hi, nice article, after reading this one I started to dig into less. I ended up with a codekyt local solution, with a file structure inspired by your.
    Now I would like to unify/minify everything ;) I just dont understand how to include plugins css into my style.css. Technically I have it done, the css are inside my style.css.
    Then what should I do to have the plugin refer to style.css instead of its own?
    Is this possible also for js files? I’m thinking about this for performance.

  • http://www.promotionalbeercoasters.com/ cakecaged

    really good

  • Dyzae

    Hi, I work with LESS recently and I don’t know if you can help me?

    My stylesheet work perfectly with LESS and I would like to change
    some variable dynamicly. I found rapidly you can do that with this
    simple code:

    less.modifyVars({
    ‘@base': ‘#fff’
    });

    It’s work, but unfortunatly… not on wordpress. He doesn’t gave me error. He just do nothing. Can you help me?

    Before you ask: Yes I imported the last version of less.js.

    [Sorry for my english, it’s not my fisrt language.]