Open In App

How to detect touch screen device using CSS ?

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • pointer: none: It gets triggered when the input mechanism of the device has no pointing device.
  • pointer: coarse: It gets triggered when the input mechanism of the pointing device has less accuracy. For example, touchscreens.
  • pointer: fine: It gets triggered when the input mechanism of the pointing device has high accuracy. For example, a mouse, trackpad, stylus, etc.

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

HTML




<!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 on the touch screen:              

Output from a smartphone 

  • Output on the non-touchscreen:

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads