CSS Responsive Web Design: Media Queries Tutorial

4/13/2025

#CSS Responsive Web Design: Media Queries Turial

Go Back
#CSS Responsive Web Design: Media Queries Turial

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.


📊 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

Feature Description
min-width Triggers when viewport is at least a certain width
max-width Triggers when viewport is at most a certain width
orientation Checks for portrait or landscape
resolution Checks device resolution (DPI)
hover Detects 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!

Table of content