5-3gaw
Last Updated: February 25, 2016
·
1.645K
· elad2412
Elad1

How to work with Modernizr and Less together

Hello everybody. In this protip I assume that most of you have used or experienced with Modernizr and Less (CSS library).

Picture

One of the feature that less gives you is nested styles. It's nice and it makes your CSS more readable and have a better structure. But there is and issue when working with Modernizr CSS classes that are found in the HTML tag.

Let's say we have this HTML & CSS, like in this example:

HTML

<div class="box">    

</div>

CSS

.box{
  width:200px;
  height:200px;
  box-shadow:0 0 5px 5px #888;
}

When it comes to working with Modernizr you have a little conflict. If you want to add treatment for example to browsers that doesn't support box-shadow, like IE8 I will need to have outline style instead of using the unsupported box-shadow (using Modernizr class).

CSS

.no-boxshadow{      
     .box{outline:solid 2px #888;}      
}

Both CSS styles parents are connected, but are written separately - see Example:

  .box{
    width:200px;
    height:200px;
    box-shadow:0 0 5px 5px #888;
  }


.no-boxshadow{      
     .box{outline:solid 2px #888;}      
}

The Solution

The solution is quite simple. We can add a parent class of Modernizr nested inside the .box class and this way our groups have connection, using the & less feature at the end of the property.

I need to add to my class box only this style

.no-boxshadow &{
  outline:solid 2px #888;
}

Full Solution

The full new style will look like this:

.box{
  width:200px;
  height:200px;
  box-shadow:0 0 5px 5px #888;

   /*Check if HTML parent has class .no-boxshadow 
      - if true add this styles*/

  .no-boxshadow &{
    outline:solid 2px #888;
  }

}

Now the less code is a lot more readable and isn't requiring to write same class doubled and separated.

That’s all, I hope you enjoy it.

If you like this post, I will be happy to get your UPVOTE. You are welcome to follow me or my team @Walla! R&D and endorse my skills.

Elad Shechter.

Say Thanks
Respond