10

Usually I use modernizr to find out the browser abilities. Same time, I use LESS CSS to make my css more readable and maintainable. Common style using LESS nested rules looks like this:

#header {
  color: black;

  .logo {
    width: 300px;
    color: rgba(255,255,255,.6);
    &:hover { text-decoration: none }
  }
}

Then, if I use modernizr style fall-back, I add this text for previous block:

.no-js #header,
.no-rgba #header {
  .logo {
    color: white;
  }
}

So, it looks like I have two branches of code, and every time I need to check another compatability aspect the number of braches will grow. This code is less maintainable, because you have to find all the styles applied to every element, and the benefit we get using nested classes disappears.

The question: is there a way in LESS syntax to include such fall-backs and not starting a new code-branch for .no-js and other .no-smth classes?

Bardt
  • 695
  • 1
  • 8
  • 17

2 Answers2

20

You can now use the & operator to address this very problem. The following syntax should work in less.js, lessphp, and dotless:

b {
  a & {
    color: red;
  }
}

This is compiled into:

a b { color:red; }

So, for the given example you could use the following syntax:

#header {
    .logo { color:white; }
    .no-rgba &,
    .no-js & {
        .logo { color:green; }
    }
}

... which would be compiled into:

#header .logo {
    color:white;
}
.no-rgba #header .logo,
.no-js #header .logo {
    color:green;
}
Michael Martin-Smucker
  • 11,927
  • 7
  • 31
  • 36
Ben
  • 2,365
  • 4
  • 22
  • 29
  • 1
    This appears to be in the main LESS project as well as the PHP version https://github.com/cloudhead/less.js/issues/127 – Chao Feb 27 '12 at 14:45
  • 1
    yay! i knew this had to exist :-) i tried searching for 'jump out of less selector' or 'escape from less selector' or 'reference root in less selector' but in the end I just realized 'modernizr less' would find this :-) – Simon_Weaver Apr 12 '14 at 20:38
  • 1
    @Simon_Weaver exactly how I found it too ! – drskullster Feb 26 '15 at 21:24
1

The best way I can think to approach it is to just have a separate .less file for these fallbacks. I think this would end up much easier to manage so you don't have to peck around for .no-rgba in lots of places.

.no-rgba {
  #header {}
  #footer {}
}

.no-js {
  #header {}
  #footer {}
}

I did try coming up with a solution how you wanted it but I had no luck.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
  • This time I think it is the best approach. I should try it in my next project. If you find something better - write me a word. Thanks for trying! – Bardt Jul 25 '11 at 17:30