CSS Responsive Web Design: Media Queries Tutorial

4/13/2025

responsive web design css

Go Back

CSS Responsive Web Design: Media Queries Tutorial

Responsive web design ensures that websites look and function well on all devices, from mobile phones to desktops. One of the key tools for achieving responsive layouts is CSS Media Queries. They allow you to apply styles based on screen size, resolution, orientation, and more.


 responsive web design css

What are Media Queries?

Media queries are conditional CSS rules that apply styles only when certain conditions are met. They are essential for creating layouts that adapt to different devices.

@media (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

In the above example, the background color changes when the viewport width is 600px or less.


Basic Syntax of Media Queries

@media media-type and (condition) {
  /* CSS rules */
}
  • media-type: usually screen, print, or all.

  • condition: features like max-width, min-width, orientation, etc.

Example:

@media screen and (min-width: 768px) {
  .container {
    width: 750px;
  }
}

Common Use Cases

1. Mobile First Design

Start with styles for small screens, then add media queries for larger screens.

/* Mobile styles (default) */
.container {
  flex-direction: column;
}

/* Tablet and up */
@media (min-width: 768px) {
  .container {
    flex-direction: row;
  }
}

2. Hide/Show Elements

@media (max-width: 480px) {
  .desktop-only {
    display: none;
  }
}

3. Change Layouts

@media (min-width: 1024px) {
  .sidebar {
    float: left;
    width: 25%;
  }
  .content {
    width: 75%;
  }
}

Useful Media Features

FeatureDescription
min-widthTriggers when viewport is at least a certain width
max-widthTriggers when viewport is at most a certain width
orientationChecks for portrait or landscape
resolutionChecks device resolution (DPI)
hoverDetects whether hover interactions are supported

Example: Responsive Navigation Menu

nav ul {
  display: flex;
  flex-direction: row;
}

@media (max-width: 768px) {
  nav ul {
    flex-direction: column;
  }
}

Tips for Effective Media Queries

  • Use relative units (em, %) instead of fixed units (px) where possible.

  • Group similar queries to avoid repetition.

  • Test across real devices and browser tools.

  • Combine with flexbox or grid for fluid layouts.


Conclusion

Media queries are the foundation of responsive design. By learning how to write flexible, adaptive styles, you can ensure your website looks great on any screen size. Start with a mobile-first mindset, define breakpoints wisely, and use tools like Chrome DevTools to fine-tune your layout. Embrace the responsive web—your users will thank you!