How to code CSS media queries targeting ALL mobile devices and tablets?

This can be done with Level 4 Media Queries: (Browser Support is quite good – CaniUse)

Interaction Media Features

The idea here is to target devices based on their capabilities. (as apposed to say, checking the size or resolution of the device which tend to be moving targets)

The pointer media feature queries the quality of the pointer mechanism used by the device.

The hover media feature queries the user’s ability to hover over elements on the page with a given device.

So to answer the question…

Mobile devices/tables are similar in that:

1) The accuracy of the primary input mechanism of the device is limited.

This means we could use the following media query:

@media (pointer:coarse) {
    /* custom css for "touch targets" */
}

div {
  width: 400px;
  height: 200px;
  color: white;
  padding: 15px;
  font-size: 20px;
  font-family: Verdana;
  line-height: 1.3;
  background: green;
}
@media (pointer:coarse) { 
  div {
    background: red;
  }
}
<h2>The <a href="https://www.w3.org/TR/mediaqueries-4/#pointer">pointer media feature</a> queries the quality of the pointer mechanism used by the device.</h2>
<div>The background here will be green on 'desktop' (devices with an accurate pointing mechanism such as a mouse) and red on 'mobile' (devices with limited accuracy of primary input mechanism) </div>

Codepen Demo

2) The primary pointing system can’t hover

So our media query would look like this:

@media (hover: none) { 
   /* custom css for devices where the primary input mechanism cannot hover 
   at all or cannot conveniently hover
}

NB: Chrome/Android prior to version 59 required the on-demand value for hover/any-hover media queries. This value was later removed from the spec and no longer required by Chrome from version 59.
So to support older versions of Android you need

@media (hover:none), (hover:on-demand) { 
  /* custom css for "touch targets" */
}

div {
  width: 400px;
  height: 150px;
  color: white;
  padding: 15px;
  font-size: 20px;
  font-family: Verdana;
  line-height: 1.3;
  background: green;
}
@media (hover:none), (hover:on-demand){ 
  div {
    background: red;
  }
}
<h2>The <a href="https://www.w3.org/TR/mediaqueries-4/#hover">hover media feature</a> queries the user’s ability to hover over elements on the page</h2>
<div>The background here will be green on 'desktop' (devices which support hover) and red on 'mobile' (devices which don't [easily] support hover ) </div>

Codepen Demo

NB:

Even if you were to connect a mouse to a mobile/tablet, the hover media feature still matches none since their primary interaction mode doesn’t support hover.

If we do want to take secondary devices into consideration we could use the any-pointer and any-hover features

So if we wanted mobile devices connected with a pointing device to be treated like a ‘desktop’ we could use the following:

@media (any-hover: hover) { ... }

Extra reading

Leave a Comment