In today’s multi-device world, websites must look great on every screen — from a large desktop monitor to a small mobile phone. That’s where CSS media queries come into play. They help you apply different styles based on the screen size, resolution, or device type.
In this blog, you’ll learn exactly how to use media queries in CSS with easy examples, best practices, and powerful tips to create fully responsive layouts.
✅ What Is a Media Query?
A media query is a CSS technique that allows you to apply styles based on specific conditions like:
- Screen width or height
- Device type
- Orientation (portrait or landscape)
- Resolution (DPI)
📌 Basic Syntax:
@media media-type and (condition) {
/* CSS rules go here */
}
🎯 Common Use Cases
- Change font size on smaller screens
- Stack elements vertically on mobile
- Hide or show specific content
- Create responsive navigation menus
🛠️ How to Use Media Queries in CSS
✅ Example 1: Change Background on Small Screens
body {
background-color: white;
}
@media (max-width: 768px) {
body {
background-color: lightgray;
}
}
👉 If the screen width is 768px or less, the background becomes light gray.
✅ Example 2: Responsive Font Sizes
h1 {
font-size: 36px;
}
@media (max-width: 600px) {
h1 {
font-size: 24px;
}
}
🎯 Result: On smaller devices, headings shrink for better readability.
✅ Example 3: Show or Hide an Element
.menu-mobile {
display: none;
}
@media (max-width: 768px) {
.menu-mobile {
display: block;
}
}
✔️ Use this to show a mobile menu only on small screens.
📏 Most Common Breakpoints (You Can Customize)
Device | Breakpoint Width |
---|---|
Extra small phones | < 480px |
Small phones | 481px – 767px |
Tablets | 768px – 1024px |
Laptops | 1025px – 1440px |
Desktops | > 1440px |
🧠 Tips for Writing Media Queries
- ✅ Mobile-first approach: Write default styles for mobile, then use
min-width
to scale up. - 🧩 Group related styles: Keep media queries close to the base styles they override.
- 🔍 Test on real devices: Emulators help, but real devices give accurate results.
- 🎯 Use relative units:
em
,rem
,%
make your layout more flexible.
💡 Advanced: Combining Conditions
You can chain conditions for more control.
@media (min-width: 600px) and (max-width: 1024px) {
.container {
padding: 40px;
}
}
📌 This applies styles only between 600px and 1024px screen width.
⚠️ Mistakes to Avoid
- ❌ Overusing too many breakpoints
- ❌ Using fixed
px
units everywhere - ❌ Forgetting to test across browsers
🔚 Conclusion
Media queries are the backbone of responsive web design. With just a few lines of code, you can make your website adapt beautifully to all screen sizes — creating a better user experience and stronger SEO performance.
📌 Quick Copy-Paste Snippet
@media (max-width: 768px) {
/* Mobile styles go here */
}