Open In App

How to detect touch screen device using CSS ?

In this article, we will learn how to detect touchscreen devices using CSS. In a website, it becomes important to detect the pointing device used by the user. For example, if the user uses a finger as the pointing device (which has less accuracy on the screen due to more screen-finger contact area) then we should increase the size of various elements like buttons, links, input fields, etc. so that the user feels comfortable using the website.

A touchscreen device can easily be detected using CSS media queries or by using JavaScript. 



HTML alone cannot detect touchscreen devices. Along with HTML, we will need CSS media queries. In CSS media queries we have a feature called pointer used to detect the pointing accuracy of the pointing device used by the user. It has the following 3 values.

Example: Here we will detect if the user is using a touchscreen device or not with the help of the above-explained approach.






<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        /* By default, setting the
            image display to none */
        #image-GFG {
            display: none;
        }
 
        /* In case of touch-screen device,
            setting image display to block.
            Using @media to detect pointer
            accuracy */
        @media (pointer:coarse) {
            #image-GFG {
                display: block;
            }
        }
    </style>
</head>
 
<body>
    <h2>
        This image will only be visible on
        a touch screen device
    </h2>
 
    <img src=
         id="image-GFG">
</body>
</html>

Output:

Output from a smartphone 

Output from a non touch-screen desktop

Note: To test output on a smartphone, copy the above code into a .html file and transfer it to the smartphone and open it using any browser like Chrome or Safari.


Article Tags :