CSS Media Queries

A media query applies CSS only when a condition is true, for example when the screen is narrower than 600 pixels. Media queries are the base of responsive design.


Syntax

@media (max-width: 600px) {
  .menu { display: none; }
  .column { width: 100%; }
}

The rules inside the braces work only when the browser window is 600px wide or less. Make sure the page has the viewport meta tag, or phones will ignore your queries.


Mobile first

Write the CSS for small screens first, then add min-width queries to improve it for bigger screens.

/* phones: one column */
.cards { display: grid; grid-template-columns: 1fr; gap: 16px; }

/* tablets */
@media (min-width: 768px) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}

/* desktops */
@media (min-width: 1100px) {
  .cards { grid-template-columns: repeat(3, 1fr); }
}

Common breakpoints

DeviceWidth
Phonesup to about 600px
Tabletsabout 768px
Laptops and desktops1024px and above

Choose breakpoints where your design starts to break, not only for specific devices.


Other useful queries

@media (orientation: landscape) { ... }          /* phone turned sideways */
@media print { nav, footer { display: none; } }   /* when printing */
@media (prefers-color-scheme: dark) {
  body { background: #111; color: #eee; }          /* visitor uses dark mode */
}
@media (prefers-reduced-motion: reduce) {
  * { animation: none; }                           /* less motion */
}
Note: Test with the browser developer tools (F12), and the device mode. Resize the window and watch the layout change.

Summary

  • @media (condition) { rules } applies rules only when the condition is true.
  • Prefer mobile first with min-width.
  • Also use queries for print, dark mode and reduced motion.
  • Related: HTML Responsive Design.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.