Open In App

Basics of Responsive Web Design - Media Queries

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Media queries in CSS are essential for creating responsive designs that adapt to different device sizes and orientations. They allow developers to apply styles based on various conditions, ensuring optimal display across different devices.

What are Media Queries?

Media queries enable conditional styling based on factors such as viewport dimensions, device characteristics (like screen width), and even user preferences. This technique ensures that styles are applied only when specific conditions are met.

Syntax:

@media only screen and (/* condition */) {    
/* CSS rules */
}

Explanation:

The @media rule is used to define a media query. Inside the parentheses, you specify conditions such as minimum or maximum width (min-width, max-width), orientation (landscape, portrait), resolution (min-resolution, max-resolution), etc.

Example:

CSS
@media only screen and (max-width: 500px) {
    body {
        background-color: black;
    }
}

In this example, the background color of the body element changes to black only when the viewport width is 500 pixels or less.

CSS
@media only screen and (min-width: 300px) and (max-width: 500px) {
    /* CSS rules */
}

This example applies styles only when the viewport width is between 300 pixels and 500 pixels.

Example: In this example, we will make a responsive web page using a media query.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            background-color: blue;
        }

        @media only screen and (min-width: 500px) and (max-width: 700px) {
            body {
                background-color: red;
            }
        }
    </style>
</head>

<body>
    <p>
        On devices with minimum width of 500px
        and maximum width of 700px, the background
        color will be black
    </p>
    <p>
        On the other hand, devices with less than the
        minimum width of 500px will have the
        body be displayed in blue
    </p>

</body>

</html>

Output: 

Media queries are very useful when you want a specific code to only execute if the conditions regarding the window's size are met. For example, if you would like the background color of the page to be black on larger devices but blue on smaller devices, then media queries are the best way to handle such cases.


Similar Reads