For some reason there is a severe dearth of information on the interwebs on how to target Android devices via CSS media queries. So what’s wrong with the following line of code?

@media (max-width: 480px) {
/* Mobile CSS goes here */

This common Media Query snippet targets all mobile devices, but unfortunately, only the new iPhone behaves well with things like pseudo-classes and advanced text transformations like -webkit-mask-image. So I needed a way to turn these features off specifically on Android phones, since not even the newest phones (SIII included) support these features.

If you do a bit of digging, you can find WebKit-specific Media Query parameters – and since Android browsers run on WebKit, we can start here. One of the properties is called -webkit-device-pixel-ratio (it’s about 10% of the way down the page), which calculates the aspect ratio of the device. Unfortunately, one of the huge pains in the ass about having Android on multiple carriers is that there are quiet a few aspect ratios – 4 of them as of August 2012. With the help of Wikipedia, I’ve created the following snippet you can use to target Android devices with CSS Media Queries.

@media only screen and (-webkit-device-pixel-ratio: .75) {
/* CSS for Low-density screens goes here *
* Ex: HTC Evo, HTC Incredible, Nexus One */
@media only screen and (-webkit-device-pixel-ratio: 1) and (max-device-width: 768px) {
/* CSS for Medium-density screens goes here *
* Ex: Samsung Ace, Kindle Fire, Macbook Pro *
* max-device-width added so you don’t target laptops and desktops */
@media only screen and (-webkit-device-pixel-ratio: 1.5) {
/* CSS for High-density screens goes here *
* Ex: Samsung Galaxy SII, HTC Nexus One, HTC Evo 3D */
@media only screen and (-webkit-device-pixel-ratio: 2) {
/* CSS for Ultra-high-density (Retina) screens goes here *
* Ex: Samsung Galaxy SIII, HTC Evo LTE, iPhone 4 */

Two things to be aware of:

  1. The additional parameter for max-device-width on medium-density devices. This is because laptops like the Macbook Air use this ratio, and you’ll need to set a further constraint to make sure you aren’t targeting laptops/desktops as well. EDIT: As someone pointed out in the comments, we’re not directly targeting Android devices. We’re using aspect ratio parameters which just so happen to belong to only Android devices. Which brings me to my second point…
  2. This does not work for the newest Android phones because they have the same aspect ratio as the iPhone. Any Android phone with an aspect ratio of 2 (e.g. Samsung Galaxy SIII, HTC Evo LTE, Samsung Galaxy Nexus) shares the same ratio and browser technology as the iPhone, since both Android and Safari use WebKit underneath the hood. Until I can find another hack, we’re SOL at the moment, but if you really need to, you can always use JavaScript to sniff the userAgent property for Android or iPhone.