Responsive on-screen keys

s1hofmann

Simon Hofmann

Posted on December 1, 2020

Responsive on-screen keys

For my most recent little game I noticed that touch input does not work that well with this type of game, but on-screen keyboards of mobile devices do not provide arrow keys, nor can they be forcefully opened without focusing input fields.
So, when played on a device with touch input (smartphone, tablet, etc.), users should be provided with dedicated on-screen keys — CSS to the rescue!

First try — Size dependent on-screen keys

In a first, naive approach I decided to generally display touch controls on smaller screens. I went with something like the following:

.on-screen-keys {
    display: none;
}
@media (max-width: 768px) {
    .on-screen-keys {
        display: inline-flex;
    }
}     
Enter fullscreen mode Exit fullscreen mode

However, screen size is not the best criteria to determine whether to display on-screen keys.

Next try — Pointer device

A better approach would be to determine whether we’re dealing with a touch device or not. A little research revealed the CSS pointer media feature, a way to determine how accurate the primary pointing device is.
Smartphones, tablets etc. which are primarily using touch input are identified as coarse input with limited accuracy, a distinction from fine input via mouse / keyboard.

.on-screen-keys {
    display: none;
}
@media (pointer: coarse) {
    .on-screen-keys {
        display: inline-flex;
    }
}
Enter fullscreen mode Exit fullscreen mode

Demo

I put together a little sample on CodePen. Don’t expect to see anything when visiting it from a device with pointer: fine, but when viewed on e.g. a tablet, you should see the same buttons as used in my game.

Conclusion

Never underestimate CSS!

💖 💪 🙅 🚩
s1hofmann
Simon Hofmann

Posted on December 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Responsive on-screen keys
javascript Responsive on-screen keys

December 1, 2020