In this tutorial, you’ll learn how to detect touch devices with CSS only.
I found this solution when I needed to write iPad specific CSS. It turned out that previous methods of detecting iPads/iPhones using User-Agent no longer work on the iPadOS. As Apple now treat iPadOS as a ‘desktop’ browser.
I’ve tried various methods but this one works really well. The idea is to check whether the device has the hover feature or not. Basically, if the user can’t hover over elements it’s a touch device.
You can test it with the following media query:
@media (hover: none) {
.class {
background: lime;
}
}
That’s it, your .class
will have a lime background colour on touch devices only.
If you want to show CSS on devices that support hover feature you can do the following:
@media (hover: hover) { // note the hover value
.class {
background: beige;
}
}
Hope it helps! Instead of using third-party JavaScript scripts and so on you can simply use the method above. It’s supported by all browsers except Internet Explorer (Edge is supported though).
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/css-detect-ipad-iphone
PS: Make sure you check other CSS tutorials, e.g. CSS3 properties that no longer need browser -prefixes-, CSS position fixed not working [solved] and how I structure SCSS files.