Open In App
Related Articles

How to target desktop, tablet and mobile using Media Query ?

Improve Article
Improve
Save Article
Save
Like Article
Like

Media Query is a popular technique that enables to deliver a style sheet to different devices which have different screen sizes and resolutions respectively. They are used to customize the appearance of a website on multiple devices. A media query consist of a media type that can contain one or more expression which can be either true or false. The result of the query is true if the specified media matches the type of device the document is displayed on. If the media query is true then the style sheet is applied.

The screen resolutions of different devices are listed below:

  • Mobile (Smartphone) max-width: 480px
  • Low Resolution Tablets and ipads max-width: 767px
  • Tablets Ipads portrait mode max-width:1024px
  • Desktops max-width:1280px
  • Huge size (Larger screen) max-width: 1281px and greater

Syntax:

@media( media feature ) {
    // CSS Property
}

It uses @media rule to include a block of CSS properties when a certain condition is true. Certain media features are width (max-width and min-width), aspect ratio, resolution, orientation, etc.

Example:

html




<!DOCTYPE html>
<html>
      
<head>
    <title>Media Query</title>
      
    <style>
          
        /* Media Query for Mobile Devices */
        @media (max-width: 480px) {
            body {
                background-color: red;
            }
        }
          
        /* Media Query for low resolution  Tablets, Ipads */
        @media (min-width: 481px) and (max-width: 767px) {
            body {
                background-color: yellow;
            }
        }
          
        /* Media Query for Tablets Ipads portrait mode */
        @media (min-width: 768px) and (max-width: 1024px){
            body {
                background-color: blue;
            }
        }
          
        /* Media Query for Laptops and Desktops */
        @media (min-width: 1025px) and (max-width: 1280px){
            body {
                background-color: green;
            }
        }
          
        /* Media Query for Large screens */
        @media (min-width: 1281px) {
            body {
                background-color: white;
            }
        }
    </style>
</head>
  
<body style = "text-align:center;">
    <h1>GeeksforGeeks</h1>
    <h2>Media Query</h2>
</body>
  
</html>                    


Output:

  • Output on Mobile Device:
  • Output on low resolution Tablets, Ipads:
  • Output on Tablets Ipads portrait mode:
  • Output on Laptops and Desktops:
  • Output on large screens:

Note: Change the screen size to see the media query effect.

Supported Browsers: The browser supported by Media Query are listed below:

  • Google Chrome 21.0
  • Internet Explorer 9.0
  • Mozilla Firefox 3.5
  • Safari 4.0
  • Opera 9.0

Last Updated : 10 Jan, 2022
Like Article
Save Article
Similar Reads
Related Tutorials