Start Coding

CSS Media Queries

CSS media queries are a powerful feature in CSS (Cascading Style Sheets) that allow web developers to create responsive and adaptive layouts. They enable the application of different styles based on various device characteristics, such as screen size, resolution, or orientation.

Understanding Media Queries

Media queries consist of a media type and one or more expressions that check for specific conditions. When these conditions are true, the corresponding styles are applied. This mechanism forms the foundation of responsive web design.

Basic Syntax

The basic syntax of a media query is as follows:

@media mediatype and (expression) {
    /* CSS rules */
}

Common media types include "screen" for computer screens, "print" for printers, and "all" for all devices. Expressions typically involve device features like width, height, or orientation.

Practical Examples

Example 1: Adjusting Layout for Different Screen Sizes

/* Default styles for mobile */
.container {
    width: 100%;
}

/* Styles for screens wider than 768px */
@media screen and (min-width: 768px) {
    .container {
        width: 750px;
        margin: 0 auto;
    }
}

In this example, the container is full-width on mobile devices. For screens wider than 768px, it becomes a fixed-width centered container.

Example 2: Changing Font Size Based on Device Orientation

body {
    font-size: 16px;
}

@media screen and (orientation: landscape) {
    body {
        font-size: 18px;
    }
}

Here, the font size increases slightly when the device is in landscape orientation, improving readability on wider screens.

Best Practices

  • Start with a mobile-first approach, defining base styles for small screens and progressively enhancing for larger ones.
  • Use relative units like em, rem, or percentages for flexible layouts.
  • Test your designs on various devices and screen sizes to ensure consistency.
  • Combine media queries with CSS Flexbox or CSS Grid for more robust responsive layouts.
  • Consider using CSS variables to manage breakpoints consistently across your stylesheet.

Common Breakpoints

While breakpoints should be tailored to your specific design, some common ranges include:

Device Typical Breakpoint
Mobile Up to 767px
Tablet 768px - 1023px
Desktop 1024px and above

Advanced Techniques

Media queries can also target specific device features like pixel ratio for high-resolution displays:

@media screen and (min-resolution: 2dppx) {
    /* Styles for high-resolution screens */
}

This query applies styles to devices with a minimum resolution of 2 dots per pixel, common in Retina displays.

Conclusion

CSS media queries are essential for creating flexible, responsive web designs. By mastering this technique, developers can ensure their websites look great and function well across a wide range of devices and screen sizes. Remember to combine media queries with other responsive design techniques for the best results.