CSS Media Queries
Media queries apply CSS only when a condition is true — usually a screen-size range. They're the core of responsive design.
Anatomy of a query
@media + a condition to make them conditional.Common breakpoints
| Range | Typical query | Targets |
|---|---|---|
| Phones | default styles | Mobile-first base styles. |
| Tablets | @media(min-width: 768px) | Tablets in portrait. |
| Small laptops | @media(min-width: 1024px) | Tablets landscape / small laptops. |
| Desktops | @media(min-width: 1280px) | Most laptops and desktops. |
| Large screens | @media(min-width: 1536px) | 4K, ultrawide. |
Beyond width
(prefers-color-scheme: dark)— user wants dark mode.(prefers-reduced-motion: reduce)— disable non-essential animations.(hover: none)— touchscreen, no precise hover.(orientation: portrait)— taller than it is wide.print— styling printed pages.
Tip: Write mobile-first: start with the small-screen layout as the default, then add
min-width queries to enhance for bigger screens. It's almost always less code than the reverse.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 Media Queries</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Run these rules only when the viewport is at least 768px wide.
@media (
: 768px) {
.card { padding: 32px; }
}
The condition that matches "this width or larger".
Discussion
Loading…