0
0
CssConceptBeginner · 3 min read

What is Media Query in CSS: Simple Explanation and Example

A media query in CSS is a way to apply different styles depending on the device's characteristics like screen size or resolution. It helps make websites look good on phones, tablets, and desktops by changing the layout or colors based on these conditions.
⚙️

How It Works

Think of a media query as a smart switch that changes your website’s style depending on the device you use. Just like how sunglasses adjust to bright sunlight, media queries check the screen size or type and apply the right CSS rules.

For example, if you open a website on a small phone screen, the media query can detect this and make text bigger or rearrange content to fit better. On a large desktop screen, it can show more details or a different layout. This way, one website can look great everywhere without needing separate versions.

💻

Example

This example changes the background color of a page depending on the screen width. If the screen is 600 pixels wide or less, the background turns light blue; otherwise, it stays white.

css
body {
  background-color: white;
}

@media (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}
Output
A white background on wide screens; a light blue background on screens 600px wide or smaller.
🎯

When to Use

Use media queries when you want your website to adapt to different devices and screen sizes. This is essential for making your site mobile-friendly and easy to read on any device.

  • Adjust font sizes for better readability on small screens.
  • Change layouts to stack content vertically on phones instead of side-by-side.
  • Hide or show elements depending on device capabilities.
  • Improve user experience by tailoring styles to device features like screen resolution or orientation.

Key Points

  • Media queries let CSS respond to device features.
  • They are the foundation of responsive web design.
  • You can test conditions like screen width, height, orientation, and resolution.
  • They help create one flexible website for all devices.

Key Takeaways

Media queries apply CSS styles based on device features like screen size.
They enable websites to look good on phones, tablets, and desktops.
Use media queries to create responsive designs that adapt layout and style.
Common conditions include max-width, min-width, orientation, and resolution.
Media queries help improve user experience across different devices.