CSS Conditionals with LessPHP + Modernizr

Shaun, Jan 31

We've been using LessPHP quite extensively for the last few months, and around the same time we learned about Modernizer (after attempting to build the same thing ourselves).

LessPHP spawns from Less.js, however we like the control/flexibility the PHP variant gave us, which is why we're using it over Less.js.  In a nutshell, LESS is a CSS compiler that allows you to write CSS a bit more naturally, and then compiles down to CSS-complaint syntax.  It offers numerous features such as mix-ins, variables, math, functions, etc..., but the coolest thing LESS gives you is the ability to "nest":

If you're unfamiliar with Modernizer, it's a Javascript library that will test various CSS3 features and append classes to the HTML tag.  You can then target classes by calling html.borderradius a.button { } and html.no-borderradius a.button { } to offer an image free solution of rounded corners to browsers than support it, and then use legacy methods if the browser doesn't.

The problem with using this in combination with less is that less  makes it really hard to do any sort of conditional on a parent class, once you're nested.  Since you're already nested in, there's no easy way to do it other than going to the bottom of the file and creating a new nested block prefixed by html.borderradius.

We've been adding onto LessPHP since we started using it, and I finally grew tired of the issue mentioned above.  I've wanted CSS conditionals for a long time, and the complexity of LessPHP/Modernizer was unnecessary.  I patched less to add a new "prepend selector", any time a selector is prepended with ^, it will automatically move that selector to the top of the scope when compiling.

Here's an example of how it works:

It's definitely a bit of a hack, but it does work.  Just don't try to nest multiple prepend selectors :).

blog comments powered by Disqus