What are CSS media queries and how do you write mobile-first queries?
· Category: HTML & CSS
Short answer
Media queries apply CSS rules based on device characteristics like viewport width. A mobile-first approach writes base styles for small screens and uses min-width media queries to enhance layouts for larger screens.
How it works
A media query consists of a media type and one or more expressions that check conditions. The styles inside the query only apply when the condition is true.
Example
/* Mobile-first base styles */
.card {
width: 100%;
padding: 1rem;
}
/* Tablet */
@media (min-width: 600px) {
.card {
width: 48%;
display: inline-block;
}
}
/* Desktop */
@media (min-width: 1024px) {
.card {
width: 31%;
}
}
Tips
- Use
min-widthfor mobile-first andmax-widthfor desktop-first. - Define breakpoints based on content, not devices.
- Use
emorremin media queries so they respond to user font-size preferences. - Test in real browsers and use DevTools device emulation for quick checks.