CSS Media Queries

CSS Media Queries allow you to apply styles based on specific conditions, such as the viewport's size, device type, and orientation. This feature is essential for creating responsive web designs that adapt to different devices.

Syntax of Media Queries

The basic syntax of a media query consists of the `@media` rule followed by the condition(s) and the styles you want to apply.


@media media-type and (condition) {
    /* CSS rules here */
}

        

Common Media Features

  • Width and Height: Use `max-width`, `min-width`, `max-height`, or `min-height` to target specific dimensions of the viewport.
  • Device Orientation: Use `orientation: landscape` or `orientation: portrait` to apply styles based on the device’s orientation.
  • Resolution: Use `min-resolution` or `max-resolution` to target devices based on screen resolution (e.g., `dpi`, `dpcm`, or `dppx`).
  • Aspect Ratio: Use `aspect-ratio` to apply styles based on the width-to-height ratio of the viewport.

Examples of Media Queries

Example: Basic Media Query


/* Apply styles for screens wider than 600px */
@media (min-width: 600px) {
    body {
        background-color: #f0f0f0;
    }
}

            

In this example, the background color of the body changes when the viewport width is greater than 600px.

Example: Media Query for Mobile Devices


/* Styles for mobile devices */
@media (max-width: 480px) {
    .navbar {
        display: block;
    }
}

            

This media query targets devices with a maximum width of 480px, changing the navbar display to block.

Example: Orientation Media Query


/* Styles for landscape orientation */
@media (orientation: landscape) {
    body {
        font-size: 1.2em;
    }
}

            

This query increases the font size for devices in landscape orientation.

Combining Media Queries

You can combine multiple media queries using commas to apply styles for different conditions simultaneously.


/* Styles for both small screens and portrait orientation */
@media (max-width: 600px), (orientation: portrait) {
    .sidebar {
        display: none;
    }
}

        

Best Practices

  • Mobile-First Approach: Start with styles for mobile devices and use min-width queries for larger screens.
  • Keep Media Queries Organized: Group related media queries together for better readability and maintenance.
  • Test Responsiveness: Always test your design on various devices and orientations to ensure a consistent experience.