Interaction media queries in CSS

2 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

Schepp (aka Christian Schaefer) recently send a tweet that surprised me. He described that it is possible to target devices that are capable of hover interactions.

It turns out that there is whole whole section called Interaction Media Features defined in the CSS spec. It defines the pointer and hover media feature.

The pointer media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, the pointer media feature must reflect the characteristics of the “primary” input mechanism, as determined by the user agent. (To query the capabilities of any available input mechanism, see the any-pointer media feature.)

The hover media feature is used to query the user’s ability to hover over elements on the page. If a device has multiple input mechanisms, the hover media feature must reflect the characteristics of the “primary” input mechanism, as determined by the user agent. (To query the capabilities of any available input mechanism, see the any-hover media feature.)

In combination these two media features can be used to detect touch screens, stylus-based screens or touchpads. That's really cool stuff. The support for these is not cross browser compatible yet (no support in Firefox at the time of writing), but treated as a progressive enhancement there might be some interesting use cases for them.

I only did a little bit of testing but these few lines of CSS work totally fine for me.

// detect if the primary input mechanism of the device
// includes a pointing device of limited accuracy
@media (pointer:coarse) {
  a {
    color: red;
  }
}

In Chrome on desktop this leads to browser default styles for link elements, but for Chrome on my Android device all links are colored red.

Personally I'm not completely sure about these features as it already screams for cross-browser incompatibilities. Additionally I'm always trying to build interfaces that work for any device not depending on input mechanisms that are available.

But as said, now that I know of these features I bet I'll come across a use case soon and when treated as an enhancement it should be fine. ;)

Tags

Load time