Responsive Web Design Media Queries


🔹 What are Media Queries?

Media Queries are a key component of Responsive Web Design (RWD). They allow you to apply different CSS rules depending on the device’s characteristics, such as:

  • Screen width

  • Device type (screen, print)

  • Orientation (portrait or landscape)

  • Resolution or pixel density

They help your layout adapt to different screen sizes, making it mobile-friendly and user-friendly across all devices.


🔸 Media Query Syntax

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

Example:

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

This changes the background color only if the screen width is 768px or less.


🔸 Common Media Features

Feature Description
max-width Applies if the screen is less than or equal to given width
min-width Applies if the screen is greater than or equal to given width
orientation Detects screen orientation: portrait or landscape
max-height Applies based on screen height
resolution Targets screen pixel density (e.g., Retina)

🔸 Example 1: Responsive Font Size

body {
  font-size: 18px;
}

@media (max-width: 600px) {
  body {
    font-size: 16px;
  }
}

🔸 Example 2: Layout Breakpoints

/* Desktop */
.container {
  display: flex;
}

/* Tablet */
@media (max-width: 992px) {
  .container {
    flex-direction: column;
  }
}

/* Mobile */
@media (max-width: 600px) {
  .container {
    padding: 10px;
  }
}

🔸 Example 3: Orientation-Based Styling

@media (orientation: landscape) {
  .video-player {
    width: 80%;
  }
}

🔸 Best Practices

✅ Use em or rem units instead of px for better scalability
✅ Start with a mobile-first approach using min-width
✅ Organize media queries by breakpoints: mobile, tablet, desktop
✅ Avoid too many breakpoints — use them only when necessary


Practice Questions

✅ Write CSS to handle these situations:

Q1. Hide a sidebar on screens smaller than 768px

Q2. Change body background color only on tablets

Q3. Resize image to 100% width on mobile devices

Q4. Stack two columns vertically on small screens

Q5. Change font size for headings on large desktops

Q6. Adjust padding and margin for small screens

Q7. Show a hamburger icon below 600px screen width

Q8. Apply dark background only in portrait mode

Q9. Make navbar fixed only on desktop

Q10. Hide a banner on screens wider than 1200px


Go Back Top