February 28, 2013

Responsive web design in a Retina world

By Kilian Frey

I’ll admit it. I thought Responsive Web Design wasn’t going to stick around more than a year, but with numbers like these who can argue its value? There are some pain points, and like any new technology, we have to work our way through these. For me, one of the biggest headaches was trying to target high pixel density displays (i.e., Retina displays) on the three different device sizes, and here’s what I’ve learned so far:


The problem

Say we want to do a responsive design where the mobile, tablet, and desktop versions all have their own set of icons for the menu bar. Our media queries would probably look something like this:

@media only screen and (max-width: 767px)  {
	 .logo {  background-image: url("logo-mobile.png"); } 
}
@media only screen and (min-width: 768px) and (max-width: 979px) { 
	 .logo {  background-image: url("logo-tablet.png");  }
}
@media only screen and (min-width: 768px)  {
	 .logo {  background-image: url("logo-desktop.png"); }
}

Now let’s say we want to have some nice juicy, high resolution icons for the mobile Retina crowd, so we add this:

@media only screen and  (-webkit-min-device-pixel-ratio: 1.5) { 
    .logo {  background-image: url("logo-mobile2x.png"); }
}

The end result is that this query will ignore the device screen size, and will apply this to all high pixel density displays, namely the Macbook Pro and iPad with Retina displays, and it ends up looking…not how we had hoped.

 

Bad media query example

…when we were hoping for this:

Good media query example

 


How we fix it…

The solution is to combine our size and pixel ratio queries into one, as follows:

@media only screen and (max-width: 767px) and (-webkit-min-device-pixel-ratio: 1.5) { 
    .logo {  background-image: url("logo-mobile2x.png"); }
}
@media only screen and (min-width: 768px) and (max-width: 979px) and (-webkit-min-device-pixel-ratio: 1.5)  { 
    .logo {  background-image: url("logo-tablet2x.png"); }
}
@media only screen and (min-width: 768px) and (-webkit-min-device-pixel-ratio: 1.5) { 
    .logo {  background-image: url("logo-desktop2x.png"); }
}

Since these media queries target the pixel ratio, we can’t just mix these in with our normal media queries. Ideally, we’d like to have these be a part of normal CSS flow, but I find it’s cleaner to have them in their own section at the beginning or end of my CSS file where I can easily edit them if something goes wrong.

Leave a Reply