CSS Media Queries
Media Queries
Media queries allow CSS to apply styles only when certain conditions are true. They are the foundation of responsive design.
The most common use is changing layout and typography at different screen widths.
@media (min-width: 768px) {
.grid {
grid-template-columns: repeat(3, 1fr);
}
}
Common Breakpoints
Breakpoints depend on your design, but a practical set is:
- 576px – small devices
- 768px – tablets
- 992px – laptops
- 1200px – large screens
Example with min-width breakpoints:
.container {
padding: 12px;
}
@media (min-width: 768px) {
.container {
padding: 18px;
}
}
@media (min-width: 992px) {
.container {
padding: 24px;
}
}
Tip: Many teams prefer mobile-first rules: write default styles for small screens, then add min-width queries for larger screens.
min-width vs max-width
min-width applies styles from the breakpoint and up. max-width applies styles up to the breakpoint.
Mobile-first (min-width):
.card {
font-size: 16px;
}
@media (min-width: 992px) {
.card {
font-size: 18px;
}
}
Desktop-first (max-width):
.card {
font-size: 18px;
}
@media (max-width: 991px) {
.card {
font-size: 16px;
}
}
Orientation
You can target device orientation:
@media (orientation: landscape) {
.hero {
min-height: 60vh;
}
}
User Preferences
Modern media queries can respect user preferences for accessibility and comfort.
Reduced motion:
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
scroll-behavior: auto !important;
}
}
Color scheme (dark mode):
@media (prefers-color-scheme: dark) {
body {
background: #0b1220;
color: #e5e7eb;
}
}
Responsive Layout Example
Simple grid that changes columns with breakpoints:
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 14px;
}
@media (min-width: 768px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 992px) {
.grid {
grid-template-columns: repeat(3, 1fr);
}
}
Summary
- Media queries apply CSS conditionally (most commonly by viewport width).
- Use mobile-first
min-widthbreakpoints for scalable responsive design. - Target orientation when needed for layout tweaks.
- Respect user preferences like
prefers-reduced-motionandprefers-color-scheme.