Todayβs web users browse on devices of all sizes – phones, tablets, laptops, desktops, and even TVs. To make sure your website looks good everywhere, you need responsive design. Thatβs where CSS media queries come in.
What Are Media Queries?
Media queries allow you to apply CSS styles based on device conditions, like screen width, height, orientation, or resolution. This makes your layout adapt to different devices.
Syntax:
@media (condition) {
/* CSS rules here */
}
Basic Media Query Example
body {
font-size: 16px;
}
@media (max-width: 600px) {
body {
font-size: 14px;
}
}
π On screens 600px wide or smaller, the font size will shrink to 14px.
Common Media Query Conditions
- max-width β Apply styles for devices up to a certain width.
- min-width β Apply styles for devices starting from a certain width.
- orientation β Detect portrait or landscape.
- resolution β Detect screen resolution (useful for high-DPI devices).
Example:
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (orientation: landscape) {
body {
background: lightblue;
}
}
Mobile-First vs. Desktop-First Approach
- Mobile-first β Start with base styles for small screens, then add
min-width
queries for larger screens. (Recommended) - Desktop-first β Start with large screens, then add
max-width
queries for smaller screens.
Example (Mobile-first):
.container {
width: 100%;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 1200px) {
.container {
width: 1100px;
}
}
Combining Multiple Conditions
You can combine conditions with and
.
@media (min-width: 600px) and (orientation: portrait) {
body {
background: lightgreen;
}
}
Responsive Images and Text
Media queries can resize images and adjust text for readability.
img {
width: 100%;
}
@media (min-width: 768px) {
img {
width: 50%;
}
}
Common Mistakes Beginners Make
- Using too many breakpoints β keep it simple.
- Forgetting mobile-first design.
- Not testing across real devices.
- Overusing
px
instead of flexible units like%
orrem
.
Quick Reference Summary
Property | Example | Description |
---|---|---|
max-width | @media (max-width: 600px) | Styles up to 600px |
min-width | @media (min-width: 768px) | Styles from 768px and up |
orientation | @media (orientation: portrait) | Detects screen orientation |
and | @media (min-width:600px) and (max-width:1200px) | Combine conditions |
Practice Challenge
- Create a responsive container:
width: 100%
on mobile750px
on tablets (min-width: 768px
)1100px
on desktops (min-width: 1200px
)
- Change background color of the page in portrait mode.
- Make images full width on mobile, half width on desktop.
Conclusion
CSS media queries are the foundation of responsive design. By adjusting layouts for different devices, you ensure your site is user-friendly everywhere – from small phones to large desktop screens.