Media queries to detect touch and non-touch (desktop) devices
A common problem that every frontend developer needs to solve is to write CSS targeting touch and non-touch devices. Over the years there have been many ways to achieve this — usually this involved using javascript libraries such as Modernizr. However, with CSS3 we have a super easy way to do this and no JS is required.
Why do I dislike the Javascript options: the short answer, bundle size.
The long answer: is it worth adding a large javascript library to your app for something we can do without a library. The answer almost always is no. Take a look at modernizr on Bundlephobia for instance:
This is a very useful and nifty library for sure and you may need it for some of your use cases however for a simple desktop vs mobile browser detection solution I think the CSS3 route is way less expensive, size-wise.
So here we go:
Let's take the use-case of showing a different header for mobile and desktop users. A classic.
Detect a touch-device with CSS3:
@media(pointer: coarse) {.mobile-header {display: block;}}
That's it. with a simple @media(pointer:coarse) you can detect any mobile device, including iPads.
Now what about desktops? easy, we can detect them using:
@media(pointer: fine) and (min-width: 950px) {.mobile-header {display: none;}}
Again, it's that simple. @media(pointer: fine) will do the trick. I used the min-width: 950px to make sure that the size of the device is big enough to qualify as a desktop computer.
Don't forget to set the default:
.mobile-header {display: none;}
Also, don't forget — you need to setup your desktop header similarly.
Bringing it all together:
@media(pointer: coarse) {.mobile-header {display: block;}}@media(pointer: fine) and (min-width: 950px) {.mobile-header {display: none;}}.mobile-header {display: none;}