Working around Android's screen.width bug

 
This android bug has been causing me trouble lately. When fetching a cached version of a page, Android sometimes sets the screen width to the previous page instead of the page you are on. This has the annoying side effect of completely ignoring your media -max-device-width CSS.

So when people first go to DuckDuckGo on their Android phone, it formats fine via the media CSS block targeted at mobile devices. Then they click on a link and click back, and all of a sudden it is no longer mobile formatted. Or they bookmark the homepage and then open it again, and the homepage isn't mobile formatted. 

I made a small demo to see the bug in action. Just visit it on your Android phone. It prints the screen.width variable out at the top--should be under 700. Then click the wiki link and wait for wikipedia to fully load. Then click back to the page (might have to do it twice to go through their mobile redirect). Now the screen.width says something different. Ugh.

I've had been trying to find a workaround off and on for a while to no avail until @amonti came up with something that works. You can (currently) just target later versions of the Android browser via CSS through a -webkit-min-device-pixel-ratio:1.5 media block, e.g.

@media only screen and (-webkit-min-device-pixel-ratio:1.5) {

I say currently because presumably other browsers may implement this feature. But in the meantime (while we wait for an Android fix) this workaround actually seems to work.

 

If you have comments, hit me up on Twitter.
I'm the Founder & CEO of DuckDuckGo, the search engine that doesn't track you. I'm also the co-author of Traction, the book that helps you get customer growth. More about me.