Modernizr & the Sass parent reference

This technique is very simple, but often overlooked because the parent reference & is mostly used at the beginning of a selector, like:

a
  color: #000

  &:hover
    color: #f00

Since & does nothing more than repeat the parent selector, it gives us an excellent way of easily implementing custom styling based on features detected by Modernizr. Just have Modernizr add class names to your <html>-tag and for instance do the following to only apply the box-shadow if the browser supports it (the box-shadow mixin comes with Compass, the .boxshadow class name will be added to your HTML by Modernizr):

#about

  h1
    border: solid 1px #000

    .boxshadow &
      border: 0
      +box-shadow(5px 5px #000)

This outputs:

#about h1 {
  border: solid 1px #000;
}

.boxshadow #about h1 {
  border: 0;
  box-shadow: 5px 5px #000;
}

A use case would be a fairly large element with a box-shadow, which makes repainting the page on iOS extremely slow. When only using a box-shadow when there's a .no-touch class name, touch devices won't have to deal with expensive shadow calculations.

Thanks for reading my blog!

If you like it, you may want to subscribe to my RSS-feed or follow me on Twitter.

blog comments powered by Disqus