Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LESS CSS syntax useful for modernizr

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?

like image 344
Bardt Avatar asked Jul 25 '11 05:07

Bardt


2 Answers

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;
}
like image 75
Ben Avatar answered Oct 27 '22 04:10

Ben


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.

like image 40
Bill Criswell Avatar answered Oct 27 '22 03:10

Bill Criswell