CSS Media Queries

Change styles at different screen sizes.

✍️ 3 exercises + code challenge in this lesson

A media query applies CSS only when a condition is true, usually the screen width.

@media (max-width: 600px) { ... } applies on screens 600px wide or smaller.

Mobile-first

A popular approach is to write styles for phones first, then add min-width queries for larger screens:

  • @media (min-width: 768px): tablets and up.
  • @media (min-width: 1024px): laptops and up.

Other conditions include orientation: landscape and prefers-color-scheme: dark.

Key Takeaways: CSS Media Queries

Mastering CSS Media Queries helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Media Queries Code Example

CSS
<style>
  .grid { display: grid; gap: 10px; grid-template-columns: 1fr; }
  .grid div { background: #14B8A6; color: white; padding: 20px; border-radius: 8px; }
  .label::after { content: "Phone layout (1 column)"; }

  @media (min-width: 500px) {
    .grid { grid-template-columns: 1fr 1fr; }
    .grid div { background: #2563EB; }
    .label::after { content: "Tablet layout (2 columns)"; }
  }
  @media (min-width: 800px) {
    .grid { grid-template-columns: repeat(4, 1fr); }
    .grid div { background: #071A2F; }
    .label::after { content: "Desktop layout (4 columns)"; }
  }
</style>

<p class="label"></p>
<div class="grid"><div>A</div><div>B</div><div>C</div><div>D</div></div>
Free sign-in required · Google login available

CSS Media Queries Practice Exercises

Check what you learned in “CSS Media Queries”.

/ 3 solved
Fill in the blank

Apply styles only on screens 600px wide or less.

@media (: 600px) {
  body { font-size: 14px; }
}
✓ Correct! Not quite. Try again.
Multiple choice

In a mobile-first approach, which media feature do you mostly use?

✓ Correct! Not quite. Try again.
Code challenge

Add a media query so the body background becomes #fef9c3 for screen devices (@media screen).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services