Skip to content
Related Articles
Open in App
Not now

Related Articles

How to detect touch screen device using CSS ?

Improve Article
Save Article
Like Article
  • Last Updated : 18 May, 2021
Improve Article
Save Article
Like Article

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, mouse, trackpad, stylus, etc.

HTML Code: The following code detects if the user is using a touchscreen device or not.

HTML




<!-- HTML code to detect a touch
    screen device  -->
<!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-touch screen:

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.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!