How to Write Mobile First Media Query in CSS
To write a
mobile first media query, start your CSS with styles for small screens by default, then use @media (min-width: value) to add styles for larger screens. This approach ensures your design works well on mobile devices first and scales up smoothly.Syntax
A mobile first media query uses the @media rule with a min-width condition. This means styles inside the query apply when the screen is at least the specified width, targeting larger devices.
@media: starts the media query(min-width: 600px): applies styles when viewport width is 600 pixels or wider- Styles outside media queries apply to all devices, usually mobile by default
css
@media (min-width: 600px) { /* styles for screens 600px and wider */ body { background-color: lightblue; } }
Example
This example shows a simple mobile first approach. The background is white on small screens. When the screen is 600px or wider, the background changes to lightblue.
css
body {
background-color: white;
font-size: 1rem;
margin: 1rem;
}
@media (min-width: 600px) {
body {
background-color: lightblue;
font-size: 1.25rem;
}
}Output
A white background on small screens that changes to light blue on screens 600px wide or larger, with larger text size on bigger screens.
Common Pitfalls
Common mistakes include:
- Using
max-widthinstead ofmin-widthfor mobile first, which targets large screens first (desktop first). - Writing all styles inside media queries instead of starting with mobile styles outside.
- Not testing on small screens first, which can cause poor mobile experience.
css
/* Wrong: desktop first approach */ @media (max-width: 600px) { body { background-color: white; } } /* Right: mobile first approach */ body { background-color: white; } @media (min-width: 600px) { body { background-color: lightblue; } }
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Mobile First | Start with styles for small screens by default | body { font-size: 1rem; } |
| Media Query | Add styles for larger screens using min-width | @media (min-width: 600px) { ... } |
| min-width | Applies styles when viewport is at least this wide | (min-width: 600px) |
| max-width | Opposite of min-width; used for desktop first | (max-width: 600px) |
Key Takeaways
Write base CSS for mobile devices first, outside any media query.
Use @media (min-width: value) to add styles for larger screens.
Avoid using max-width for mobile first; it targets desktop first.
Test your design on small screens before scaling up.
Mobile first ensures better performance and user experience on phones.