logo

Always Twisted

{ Slightly Bizarre Ramblings Of A Front-End Developer }

Everyday I'm Bubbling. With Media Queries and LESS

We're all in love with content first, mobile first, insert your buzzword of choice, responsive web design aren't we? We all know that we should (or shouldn't) be using common breakpoints.

We also know that we should be doing what Stephen Hay puts so eloquantly -

"Start with the small screen first, then expand until it looks like shit. Time to insert a breakpoint!"

Now, we could just add that new media query breakpoint in our CSS with it's relevant min-width and even with it's max-width point like we have since we've started using media queries. Or we could get bubbling.

Pretty Bubbles in the air.

With an update to LESS in February. Alexis, the creator of LESS, included media query bubbling from a pull request. This means you can now write your LESS code with the media query within the element and when you compile it'll create a seperate media query for each one you create. So, you would now write your LESS like this -


header { 
    color: red; 
	
	@media only screen and (min-width : 768px) { color: green; } 
		
	@media only screen and (min-width : 1024px) { color: blue; }
		
}

section { 
    color: green; 
	
	@media only screen and (min-width : 768px) { color: blue; } 
		
	@media only screen and (min-width : 1024px) { color: red; }
		
}

After doing all our LESS like this and compiling it, it will create this, for the above example -


header {
  color: red;
}
@media only screen and (min-width: 768px) {
  header {
    color: green;
  }
}
@media only screen and (min-width: 1024px) {
  header {
    color: blue;
  }
}

section {
  color: green;
}
@media only screen and (min-width: 768px) {
  section {
    color: blue;
  }
}
@media only screen and (min-width: 1024px) {
  section {
    color: red;
  }
}

As you can see it creates a seperate media query for whatever has a media query. It doesn't 'group' them all together as we currently do when coding by hand.

I can see a real benefit of this being created in your stylesheet, as you can see easily what elements are being changed by what media query and how at a glance. This could be more difficult when your media queries are in seperate styleshets or in 'big chunks' or media queries.

Another benefit would be when we go back and look at Stephen's quote. When your design starts to 'look shit'  using this technique would be just that little be cleaner and quicker to do.

I've yet to do any performance or 'stress' tests on actual CSS files created this way rather than the 'big chunks' we've been creating thus far but hope to do this soon.

Did you like this post? Hire me.
blog comments powered by Disqus

Did you like this post? Why not share it on twitter -

Or, why not follow me on twitter too -