SCSS vs LESS. Part: 2 Nesting

SCSS vs LESS. Part: 2

Nested Rules

Nesting CSS rules can be handy in any web implementation. Rather than having many long CSS definitions you can simply use nested rules. This allows for visually clear inheritance in your code.

However, used incorrectly will see your compiled CSS have large chunks of over qualified CSS selectors in turn bloating your CSS by sizeable amounts and slowing down your website. eg.

.boom .bing .bam{
  a{
    color: hsl(0, 100%, 50%);
  }
  #unique{
    color: hsl(0, 50%, 50%);
  }
}

Above I require the ID #unique to be referenced in this section of CSS. This markup may look neat. However once compiled It will look like this:

.boom .bing .bam a {
  color: #ff0000;
}
.boom .bing .bam #unique {
  color: #bf4040;
}

As you can see the second rule is over qualified. The ID being unique can be used by itself. A bit of trap for preprocessor rookies. Also problematic to fix in large SCSS/LESS files.

Both SCSS and LESS have a very similar syntax for nesting. For chaining selectors use an ampersand. eg.

 // SCSS/LESS  .boom input{
 color: black;
 &[type="password"]{
   border: dotted red 1px;
 }
 &.large{
   padding: 10px;
 }
 &:hover{
   background: red;
 }
}

Will output as:

.boom input {
   color: black;
 }
 .boom input[type="password"] {
   border: dotted red 1px;
 }
 .boom input.large {
   padding: 10px;
 }
 .boom input:hover {
   background: red;
 }

SCSS allows you to use an ampersand to reference the nested parent anywhere in the nested selector. Where LESS only supports this as a first character as defined in the previous example.

//SCSS Only
a {
 color: red;
 &:hover{
   text-decoration: underline;
 }
 body.ie6 & {
   color: green;
 }
}

This will allow you to reference Modernizr tags or Browser conditional Classes.

a {
 color: red;
 }
 a:hover {
   text-decoration: underline;
 }
 body.ie6 a {
   color: green;
}

Nested Properties

SCSS has a feature that is not supported by LESS and that is nested CSS properties. I’m a fan of shorthand properties. However this is a neat feature to have in the toolkit.

// SCSS
a:hover {
 transition:{
   property: font-size;
   duration: 4s;
   delay: 2s;
 }
 font-size: 36px;
}

This allows you to nest any property with a dash (according to the documentation). The complied code is below:

a:hover {
 transition-property: font-size;
 transition-duration: 4s;
 transition-delay: 2s;
 font-size: 36px;
}

Conclusion

SCSS and LESS are almost identical in nesting their selectors. Apart from SCSS’s extra functionally with referencing the parent selector they are almost identical. That said, SCSS is much better at nesting with the added functionality of property nesting. SCSS is everything LESS is plus more. Winner: SASS (SCSS).