Media Queries Basics

What a Media Query Does

A media query applies a block of CSS only when a condition about the browser or device is true - most commonly, the width of the viewport. This is the core mechanism behind responsive design.

.sidebar {
  width: 300px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100%;
  }
}

Here, the sidebar is 300px wide normally, but becomes full width once the viewport shrinks to 768px or narrower.

Common Conditions to Test

ConditionApplies when...
max-width: 768pxViewport is 768px or narrower
min-width: 1024pxViewport is 1024px or wider
orientation: landscapeWidth is greater than height
prefers-color-scheme: darkUser's system is set to dark mode

The Viewport Meta Tag Prerequisite

<meta name="viewport" content="width=device-width, initial-scale=1">

Without this tag in the HTML head, mobile browsers render the page at a zoomed-out desktop width by default, and media queries based on viewport width will not behave as expected.

Combining Multiple Conditions

@media (min-width: 600px) and (max-width: 900px) {
  /* applies only in this specific range - a "tablet" band */
}
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.