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;
    }
}     

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;
    }
}

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!