CSS Media Queries Explained

Learn how CSS media queries enable responsive web design. Understand syntax, best practices, and practical examples for adaptable layouts.


Back to Home

Table of content

Introduction to CSS Media Queries

Responsive web design is essential in today’s multi-device world. CSS media queries are the core technique that allow developers to create layouts and styles that adapt to any screen size, from desktop monitors to tiny smartphones. Whether you’re a beginner or refreshing your knowledge, understanding media queries is crucial for modern web development.

What Are CSS Media Queries?

Media queries are CSS rules that apply styles only if certain conditions about the device or viewport are met. They enhance your stylesheets by making your website adjust seamlessly to different devices.

Basic Syntax of Media Queries

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

The most common condition is max-width or min-width of the viewport.

Example: Simple Responsive Rule

.container {
  width: 80%;
}
@media (max-width: 600px) {
  .container {
    width: 100%;
  }
}

This changes the container to full width on screens up to 600px wide (e.g., most smartphones).

Common Media Features

  • Width/Height: max-width, min-width, max-height, min-height
  • Device Orientation: orientation: landscape or portrait
  • Resolution: min-resolution for targeting retina or high-DPI screens
  • Color: prefers-color-scheme for dark/light mode

Example: Orientation and Resolution

@media (orientation: landscape) {
  body {
    background: #f5f5f5;
  }
}
@media (min-resolution: 2dppx) {
  .logo {
    background-image: url('logo@2x.png');
  }
}

Responsive Breakpoints: Best Practices

  • Choose breakpoints based on your content, not device sizes.
  • Mobile-first design: Start with global styles for small screens, then use min-width to add desktop styles.
  • Keep media query logic organized in your CSS for maintainability.

Mobile-First Example

.menu {
  display: block;
}
@media (min-width: 768px) {
  .menu {
    display: flex;
  }
}

Advanced: Combining Media Queries

@media (min-width: 600px) and (orientation: landscape) {
  .gallery {
    grid-template-columns: repeat(4, 1fr);
  }
}

You can combine multiple conditions for precise targeting.

Testing and Debugging Media Queries

  • Use browser developer tools to toggle device modes and screen sizes.
  • Test across a range of devices and browsers to ensure consistency.

Conclusion

CSS media queries are the foundation of responsive web design. Mastering their syntax and using them wisely allows you to deliver adaptable, user-friendly websites for everyone, everywhere.

Want to learn more? Check out MDN’s guide to media queries for in-depth resources and advanced examples.

CSS Media Queries
CSS Tutorials
Frontend
Responsive Design
Web Development