In today’s multi-device world, designing your website to look good on all screen sizes — mobile, tablet, laptop, and desktop — is crucial. This is where Responsive Design comes in, and CSS media queries are the most powerful tool to help you adapt your styles based on the device’s screen size.
In this blog post, you’ll learn how to change CSS based on screen size using media queries, with clear examples and best practices.
🔧 What Are Media Queries?
Media queries are CSS rules that apply styles only when certain conditions are met — such as screen width, height, orientation, or resolution.
🔤 Syntax:
@media (condition) {
/* CSS styles go here */
}
✅ Basic Example – Change Text Color Based on Screen Width
📄 CSS:
p {
color: black;
}
@media (max-width: 600px) {
p {
color: blue;
}
}
🧠 Explanation:
- Default text color is black.
- When the screen is 600px wide or less, the text turns blue.
📱 Common Breakpoints for Devices
Device | Breakpoint (max-width) |
---|---|
Mobile phones | 480px – 600px |
Tablets | 768px |
Small laptops | 1024px |
Desktops | 1200px and above |
🧾 Example:
/* Styles for tablets */
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
/* Styles for phones */
@media (max-width: 480px) {
.container {
flex-direction: column;
font-size: 14px;
}
}
🎨 Responsive Layout Example
<div class="responsive-box">Resize the screen!</div>
.responsive-box {
width: 60%;
margin: auto;
padding: 20px;
background-color: lightgreen;
text-align: center;
font-size: 24px;
}
@media (max-width: 768px) {
.responsive-box {
background-color: lightblue;
font-size: 18px;
}
}
@media (max-width: 480px) {
.responsive-box {
background-color: lightcoral;
font-size: 14px;
}
}
🎯 Why Use Media Queries?
- ✅ Adjust font sizes for better readability
- ✅ Change layouts for mobile navigation
- ✅ Hide/show elements based on screen size
- ✅ Improve overall user experience
🧠 Tips for Using Media Queries
- Always start with a mobile-first approach:
- Write default styles for small screens first, then add media queries for larger screens.
- Group related queries logically.
- Use relative units (
em
,rem
,%
) instead of fixed pixels when possible. - Test on real devices and emulators.
🚀 Conclusion
CSS media queries let you customize the appearance of your website based on screen size, making it fully responsive. Whether you’re hiding a menu, resizing text, or rearranging layout components, media queries give you precise control for every device.
Responsive design is no longer optional — it’s a must-have. Mastering media queries is the first step toward building modern, user-friendly websites.