iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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 (min-width: 768px) { /* rules */ } at-rule condition (apply only when viewport >= 768px)
Fig 1. Wrap rules in @media + a condition to make them conditional.

Common breakpoints

RangeTypical queryTargets
Phonesdefault stylesMobile-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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Run these rules only when the viewport is at least 768px wide.

@media ( : 768px) { .card { padding: 32px; } }

Test yourself

Q1. Which at-rule starts a media query?
Q2. Which approach is "mobile-first"?
Q3. Which media feature respects a user's "reduce motion" setting?

Discussion

Loading…