CSS MQ Examples
A short collection of media queries that come up in almost every project.
Recipes
Mobile-first breakpoints
@media (min-width: 640px) { /* sm */ }
@media (min-width: 768px) { /* md */ }
@media (min-width: 1024px) { /* lg */ }
@media (min-width: 1280px) { /* xl */ }
Dark mode
@media (prefers-color-scheme: dark) {
:root { --bg: #111; --fg: #eee; }
}
Reduced motion
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
Print stylesheet
@media print {
nav, .ads, footer { display: none; }
a::after { content: " (" attr(href) ")"; }
}
Touch device (no hover)
@media (hover: none) {
.tooltip { display: none; } /* hover-only UI doesn't make sense */
}
High-DPI screens
@media (min-resolution: 2dppx) {
.logo { background-image: url('logo@2x.png'); }
}
Tip: Don't memorise breakpoints — derive them from your content. Where does the layout look awkward? Add a query there.
Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS MQ Examples</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Target users who prefer their OS in dark mode.
@media (prefers-color-
: dark) { /* … */ }
A single word meaning "system".
Discussion
Loading…