Mono has closed its doors. Read more in our blogpost.

Go to main content

Optimizing for touch – now detectable with CSS

For years I’ve told people that it’s impossible to detect touch accurately.

The old schoolers here might remember that at some point there was a solution using modernizr.js.

What this piece of Javascript would do was add a class of touch or no-touch to the <html> element which you could then use in your CSS to change something based on whether the user was using a touch device or not.

This got problematic when we had popular devices that both had touch and pointers like Microsoft’s Surface Pro line. The detection was not very accurate.

When Windows 10 released they announced that in Windows you could switch to “tablet mode”. What they do in tablet mode for instance is to change the tappable area of context menus.

The context menu in Windows 10. In a mouse context (left) it is smaller than in a touch context (right).

This was an interesting design pattern that stayed with me.

It seems like we might finally be able to do accurate detection of a touch context soon. In a tweet by Lea Verou she talked about the pointer media query. I tested it, and lo and behold, it works as I expected:

Here is some relevant CSS code:

/**
 * Test pointer media query
 */

/* For testing purposes: render support */
body::before {
    content: var(--pointer, "Does not support pointer MQ");
}
@media (pointer: coarse) {
    /* Code for touch devices */
}

@media (pointer: fine) {
    /* Code for non-touch devices */
}

This works in Chrome and Safari, and is going to land in Firefox soon.

I am curious how it deals with “dynamic” touch context usage (i.e. going back and forth between touch and a pen). I don’t expect much in this regard – I am already happy to be able to detect touch in a standards-based way that does not rely on Javascript.

Johan Ronsse

About the author

Johan Ronsse is an interface designer who is trying to find the balance between aesthetics and usability. He tweets as @wolfr_2.

Subscribe to our newsletter

Receive blog highlights and fresh insights into UX/UI and front-end development.

Leave a comment

Your email address will not be published. Required fields are marked *