Skip to content

CSS Tutorial CSS Responsive Design

CSS Media Queries

Lesson 110 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

A media query is an if for your CSS: “apply these rules only when this condition is true.”

style.css
CSS
@media (min-width: 768px) {
  .sidebar { display: block; }
}

The rules inside the braces apply when the screen is at least 768px wide.

Try it

The Result panel is narrow, so this example uses 400px. Change the number and press Run.

index.html
HTML
<style>
  .box { padding: 16px; background: #d0e8f2; color: #1a5276; font-weight: bold; }
  @media (min-width: 400px) {
    .box { background: #d94a00; color: #fff; }
  }
</style>
<div class="box">Blue when narrow, orange when the panel is 400px or wider.</div>

The common conditions

ConditionTrue when
(min-width: 768px)The viewport is 768px wide or more
(max-width: 767px)The viewport is 767px wide or less
(orientation: landscape)The screen is wider than tall
(prefers-color-scheme: dark)The visitor uses a dark theme
(prefers-reduced-motion: reduce)The visitor asked for less animation
printWhen printing the page

You can combine conditions with and: @media (min-width: 600px) and (max-width: 900px).

Where to put them

Media queries can sit at the bottom of the stylesheet, or beside the rule they change. Either works. The important rule is the cascade: the media query rule has the same strength as the normal rule, so it has to come after it in the file to win.

style.css
PHP
.menu { display: none; }

@media (min-width: 768px) {
  .menu { display: flex; }   /* wins because it is later */
}

min-width or max-width?

Both are fine, but pick one direction and stay with it. Most developers choose min-width, which leads to the approach in the next lesson, Mobile First.

warning
Mixing the two directions
A stylesheet with some max-width and some min-width queries is hard to follow, and queries can overlap or leave gaps. Stick to one.