LearnContact
Lesson 2324 min read

CSS Media Queries

Learn how CSS media queries create responsive websites that adapt to different screen sizes, devices, orientations, and user preferences.

Introduction

People visit websites using phones, tablets, laptops, desktop monitors, televisions, and many other devices.

A layout that looks excellent on a large desktop screen may become difficult to use on a small mobile screen.

CSS Media Queries allow a website to apply different styles when specific device or viewport conditions are true.

Browser Loads Page
Measure Viewport
Check Media Conditions
Find Matching Queries
Apply Matching CSS
Render Responsive Layout
One Website, Many Screen Sizes

Media queries allow the same HTML document to adapt its layout and appearance for different devices and viewing conditions.

What is Responsive Design?

Responsive Web Design is an approach where a website automatically adapts its layout, content, spacing, typography, and navigation to different screen sizes.

Mobile

Content may appear in a single column with compact spacing.

Tablet

Layouts may use two columns and medium spacing.

Laptop

More horizontal space allows larger multi-column layouts.

Desktop

Wide screens can display navigation, sidebars, and multiple content areas.

Responsive Layout Concept
Mobile

┌─────────────┐
│   Header    │
├─────────────┤
│   Content   │
├─────────────┤
│   Sidebar   │
├─────────────┤
│   Footer    │
└─────────────┘


Desktop

┌───────────────────────────────┐
│            Header             │
├────────────────────┬──────────┤
│                    │          │
│      Content       │ Sidebar  │
│                    │          │
├────────────────────┴──────────┤
│            Footer             │
└───────────────────────────────┘

What is a Media Query?

A media query is a CSS rule that applies styles only when one or more conditions are true.

Simple Media Query
@media (max-width: 768px) {
    .container {
        padding: 20px;
    }
}

In this example, the padding is applied only when the viewport width is 768 pixels or smaller.

Why Do We Need Media Queries?

Mobile Layouts

Convert wide desktop layouts into mobile-friendly structures.

Readable Text

Adjust typography for different screen sizes.

Better Navigation

Change large navigation menus into compact mobile menus.

Flexible Components

Resize and rearrange cards, grids, sidebars, and sections.

Device Capabilities

Adapt interactions based on hover and pointer capabilities.

User Preferences

Respond to dark mode and reduced-motion preferences.

Real-World Analogy

Imagine a restaurant with movable tables.

When only a few customers arrive, tables can remain separated. When a large group arrives, the tables can be rearranged.

The furniture remains the same, but its arrangement changes according to the available space.

RestaurantResponsive Website
Available room spaceViewport size
Tables and chairsHTML elements
Arrangement rulesCSS rules
Check available spaceMedia query condition
Rearrange furnitureApply responsive styles

Basic Media Query Syntax

Syntax
@media (condition) {
    selector {
        property: value;
    }
}
Example
.box {
    width: 500px;
}

@media (max-width: 600px) {
    .box {
        width: 100%;
    }
}
Normal CSS Still Applies

Media query styles do not replace the entire stylesheet. They participate in the normal CSS cascade and override matching rules when appropriate.

How Media Queries Work

Browser Reads CSS
Find @media Rule
Evaluate Condition
Condition True?
Apply Styles
Render Updated Layout
Media Query Decision
Viewport Width
      │
      ▼
Is Width ≤ 768px?
      │
   ┌──┴──┐
   │     │
  Yes    No
   │     │
   ▼     ▼
Apply   Ignore
Mobile  Mobile
Styles  Styles

The @media Rule

The @media rule creates a conditional block of CSS.

@media Rule
@media screen and (max-width: 768px) {
    body {
        font-size: 16px;
    }
}
PartPurpose
@mediaStarts the media query
screenSpecifies the media type
andCombines conditions
(max-width: 768px)Defines the media feature condition
{ }Contains conditional CSS rules

Media Types

Media TypePurpose
allAll devices
screenScreens such as phones, tablets, and monitors
printPrinted pages and print preview
Print Styles
@media print {
    nav,
    .advertisement {
        display: none;
    }

    body {
        color: black;
        background: white;
    }
}

Media Features

FeatureChecks
widthExact viewport width
min-widthMinimum viewport width
max-widthMaximum viewport width
heightExact viewport height
min-heightMinimum viewport height
max-heightMaximum viewport height
orientationPortrait or landscape
aspect-ratioViewport width-to-height ratio
hoverWhether hover is available
pointerPointer accuracy
prefers-color-schemeLight or dark preference
prefers-reduced-motionReduced motion preference

Viewport Width

Viewport width is the visible width of the browser area where the webpage is displayed.

Viewport Concept
Browser Window

┌───────────────────────────────┐
│◄────── Viewport Width ──────►│
│                               │
│        Website Content        │
│                               │
└───────────────────────────────┘

max-width

The max-width condition matches when the viewport is equal to or smaller than the specified width.

max-width
@media (max-width: 768px) {
    .sidebar {
        display: none;
    }
}
Condition
Viewport Width

320px ─────────────── 768px ─────────────── 1440px

◄──── Query Matches ────►│
                         │
                    max-width: 768px

Example 1: max-width

HTML
<div class="responsive-box">
    Resize the screen
</div>
CSS
.responsive-box {
    padding: 40px;

    background: #6c5ce7;
    color: white;

    font-size: 2rem;

    text-align: center;

    border-radius: 16px;
}

@media (max-width: 600px) {
    .responsive-box {
        padding: 20px;

        background: #00b894;

        font-size: 1.2rem;
    }
}

min-width

The min-width condition matches when the viewport is equal to or larger than the specified width.

min-width
@media (min-width: 768px) {
    .container {
        display: flex;
    }
}
Condition
Viewport Width

320px ─────────────── 768px ─────────────── 1440px

                         │◄──── Query Matches ────►
                         │
                    min-width: 768px

Example 2: min-width

CSS
.card-container {
    display: block;
}

@media (min-width: 768px) {
    .card-container {
        display: grid;

        grid-template-columns:
            repeat(2, 1fr);

        gap: 20px;
    }
}

@media (min-width: 1200px) {
    .card-container {
        grid-template-columns:
            repeat(4, 1fr);
    }
}

Width Ranges

The min-width and max-width features can be combined to target a specific range of viewport widths.

Width Range
@media (
    min-width: 600px
) and (
    max-width: 900px
) {
    .box {
        background: #00b894;
    }
}

Example 3: Width Range

CSS
.range-box {
    background: #6c5ce7;
}

@media (
    min-width: 600px
) and (
    max-width: 900px
) {
    .range-box {
        background: #00b894;
    }
}
Both Conditions Must Be True

When conditions are connected with and, every condition must match before the CSS block is applied.

What is a Breakpoint?

A breakpoint is a viewport width where the layout needs to change to remain usable and visually clear.

Breakpoint Concept
Mobile        Tablet         Desktop

320px         768px           1200px
  │             │                │
  ▼             ▼                ▼

Single        Two             Multiple
Column        Columns         Columns

        Layout Changes
        at Breakpoints

Choosing Breakpoints

Breakpoints should be chosen based on when the content and layout need adjustment rather than targeting specific device models.

Let the Content Decide

Resize the layout and add a breakpoint when the design becomes cramped, difficult to read, or visually unbalanced.

Common Breakpoint Examples

Example RangeTypical Layout
Below 576pxSmall mobile layout
576px and aboveLarge mobile layout
768px and aboveTablet layout
992px and aboveLaptop layout
1200px and aboveDesktop layout
1400px and aboveLarge desktop layout
These Are Not Universal Rules

Common breakpoint values are useful starting points, but every project should choose breakpoints according to its actual content and layout.

Mobile-First Design

Mobile-first design starts with styles for small screens and progressively adds layout features for larger screens.

Mobile-First Structure
.container {
    display: block;
}

/* Tablet and larger */
@media (min-width: 768px) {
    .container {
        display: grid;

        grid-template-columns:
            repeat(2, 1fr);
    }
}

/* Desktop and larger */
@media (min-width: 1200px) {
    .container {
        grid-template-columns:
            repeat(4, 1fr);
    }
}
Write Mobile Styles
Add min-width Breakpoint
Enhance Tablet Layout
Add Larger Breakpoint
Enhance Desktop Layout

Example 4: Mobile-First

CSS
.products {
    display: grid;

    grid-template-columns: 1fr;

    gap: 16px;
}

@media (min-width: 600px) {
    .products {
        grid-template-columns:
            repeat(2, 1fr);
    }
}

@media (min-width: 1000px) {
    .products {
        grid-template-columns:
            repeat(4, 1fr);
    }
}

Desktop-First Design

Desktop-first design starts with styles for large screens and progressively simplifies the layout for smaller screens.

Desktop-First Structure
.container {
    display: grid;

    grid-template-columns:
        repeat(4, 1fr);
}

@media (max-width: 992px) {
    .container {
        grid-template-columns:
            repeat(2, 1fr);
    }
}

@media (max-width: 576px) {
    .container {
        grid-template-columns:
            1fr;
    }
}

Example 5: Desktop-First

CSS
.gallery {
    display: grid;

    grid-template-columns:
        repeat(4, 1fr);

    gap: 20px;
}

@media (max-width: 900px) {
    .gallery {
        grid-template-columns:
            repeat(2, 1fr);
    }
}

@media (max-width: 500px) {
    .gallery {
        grid-template-columns:
            1fr;
    }
}

Mobile-First vs Desktop-First

Mobile-First

  • Starts with small-screen styles.
  • Usually uses min-width queries.
  • Adds complexity as space increases.
  • Common in modern responsive development.

Desktop-First

  • Starts with large-screen styles.
  • Usually uses max-width queries.
  • Removes complexity as space decreases.
  • Can be useful for desktop-focused designs.

Responsive Typography

Typography can change at different viewport sizes to maintain readability and visual balance.

Responsive Typography
h1 {
    font-size: 2rem;
}

@media (min-width: 768px) {
    h1 {
        font-size: 3rem;
    }
}

@media (min-width: 1200px) {
    h1 {
        font-size: 4rem;
    }
}

Example 6: Responsive Text

CSS
.responsive-title {
    font-size: 2rem;
}

@media (min-width: 700px) {
    .responsive-title {
        font-size: 3rem;
    }
}

@media (min-width: 1100px) {
    .responsive-title {
        font-size: 4rem;
    }
}

Responsive Navigation

Navigation often changes significantly between mobile and desktop layouts.

Navigation Change
Mobile

┌──────────────────────┐
│ Logo              ☰  │
└──────────────────────┘


Desktop

┌────────────────────────────────────┐
│ Logo    Home  Courses  About  Login│
└────────────────────────────────────┘

Example 7: Responsive Navbar

HTML
<nav class="navbar">
    <div class="logo">
        PrograMinds
    </div>

    <button class="menu-button">
        ☰
    </button>

    <div class="nav-links">
        <a href="#">Home</a>
        <a href="#">Courses</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
    </div>
</nav>
CSS
.navbar {
    display: flex;

    align-items: center;

    justify-content:
        space-between;

    padding: 16px 20px;

    background: #2d3436;
    color: white;
}

.nav-links {
    display: none;
}

.menu-button {
    display: block;
}

@media (min-width: 768px) {
    .nav-links {
        display: flex;

        gap: 24px;
    }

    .menu-button {
        display: none;
    }
}

Responsive Flexbox

Media queries can change flex direction, alignment, wrapping, and spacing according to the available width.

Example 8: Responsive Flex Layout

CSS
.flex-layout {
    display: flex;

    flex-direction: column;

    gap: 20px;
}

@media (min-width: 768px) {
    .flex-layout {
        flex-direction: row;
    }
}

Responsive Grid

Media queries can change the number and size of CSS Grid columns at different viewport widths.

Example 9: Responsive Grid

CSS
.grid {
    display: grid;

    grid-template-columns:
        1fr;

    gap: 20px;
}

@media (min-width: 600px) {
    .grid {
        grid-template-columns:
            repeat(2, 1fr);
    }
}

@media (min-width: 1000px) {
    .grid {
        grid-template-columns:
            repeat(3, 1fr);
    }
}

Orientation

The orientation media feature checks whether the viewport is wider than it is tall or taller than it is wide.

ValueMeaning
portraitHeight is greater than or equal to width
landscapeWidth is greater than height

Example 10: Orientation

CSS
@media (orientation: portrait) {
    .hero {
        flex-direction: column;
    }
}

@media (orientation: landscape) {
    .hero {
        flex-direction: row;
    }
}

Height Queries

Media queries can also respond to viewport height.

Maximum Height
@media (max-height: 500px) {
    .hero {
        min-height: auto;

        padding: 30px;
    }
}

Aspect Ratio

The aspect-ratio media feature checks the relationship between viewport width and height.

Aspect Ratio Query
@media (
    min-aspect-ratio: 16 / 9
) {
    .hero {
        min-height: 80vh;
    }
}

Hover Capability

The hover media feature checks whether the primary input device can conveniently hover over elements.

Hover Query
@media (hover: hover) {
    .card:hover {
        transform:
            translateY(-8px);
    }
}
Useful for Touch Devices

Hover-based effects can be limited to devices that actually support convenient hovering.

Pointer Capability

ValueMeaning
noneNo primary pointing device
coarseLow-accuracy pointer such as a finger
fineHigh-accuracy pointer such as a mouse
Larger Touch Targets
@media (pointer: coarse) {
    button {
        min-height: 48px;

        padding:
            14px 20px;
    }
}

Color Scheme Preference

The prefers-color-scheme media feature detects whether the user prefers a light or dark interface.

Color Scheme Query
@media (
    prefers-color-scheme: dark
) {
    body {
        background: #1e272e;

        color: #f5f6fa;
    }
}

Example 11: Dark Mode

CSS
.theme-card {
    background: white;

    color: #2d3436;
}

@media (
    prefers-color-scheme: dark
) {
    .theme-card {
        background: #2d3436;

        color: white;
    }
}
Automatic Preference Detection

This media query can adapt the interface according to the operating system or browser color scheme preference.

Reduced Motion

The prefers-reduced-motion media feature detects whether the user prefers less non-essential motion.

Example 12: Reduced Motion

CSS
.card {
    animation:
        float
        2s
        ease-in-out
        infinite
        alternate;
}

@media (
    prefers-reduced-motion: reduce
) {
    .card {
        animation: none;
    }
}

Logical Operators

OperatorPurpose
andRequires multiple conditions to match
notNegates a media query
,Works like OR between queries

The and Operator

and Operator
@media (
    min-width: 600px
) and (
    max-width: 900px
) {
    .box {
        display: flex;
    }
}

The not Operator

not Operator
@media not print {
    .interactive-controls {
        display: flex;
    }
}

Comma Operator

A comma separates alternative media queries. The styles apply when any one of the queries matches.

OR Condition
@media (
    max-width: 600px
),
(
    orientation: portrait
) {
    .sidebar {
        display: none;
    }
}

Multiple Conditions

Multiple Conditions
@media screen
    and (min-width: 768px)
    and (orientation: landscape) {

    .dashboard {
        grid-template-columns:
            250px 1fr;
    }
}

Range Syntax

Modern media queries can use comparison operators to express width ranges more naturally.

Modern Range Syntax
@media (width >= 768px) {
    .container {
        display: grid;
    }
}

@media (
    600px <= width <= 900px
) {
    .container {
        gap: 30px;
    }
}

Responsive Images

Images should usually shrink when their container becomes narrower.

Responsive Image
img {
    max-width: 100%;

    height: auto;
}

Example 13: Responsive Image

HTML
<div class="image-container">
    <img
        src="landscape.jpg"
        alt="Mountain landscape"
    >
</div>
CSS
.image-container img {
    display: block;

    max-width: 100%;

    height: auto;

    border-radius: 16px;
}

Hide and Show Elements

Media queries can hide or show interface elements at different screen sizes.

Example 14: Hide on Mobile

CSS
.desktop-sidebar {
    display: block;
}

@media (max-width: 768px) {
    .desktop-sidebar {
        display: none;
    }
}
Do Not Hide Essential Content

Responsive design should improve access to content. Important information should not disappear simply because the screen is smaller.

Responsive Spacing

Responsive Padding
.section {
    padding: 40px 20px;
}

@media (min-width: 768px) {
    .section {
        padding: 70px 40px;
    }
}

@media (min-width: 1200px) {
    .section {
        padding: 100px 60px;
    }
}

Responsive Containers

Responsive Container
.container {
    width: min(
        100% - 40px,
        1200px
    );

    margin-inline: auto;
}

A responsive container can combine fluid width with a maximum readable width, reducing the need for many width-specific media queries.

Complete Responsive Example

The following example combines a responsive navigation bar, hero section, card grid, mobile-first breakpoints, flexible typography, and responsive spacing.

HTML
<div class="responsive-page">
    <nav class="main-nav">
        <a
            href="#"
            class="brand"
        >
            PrograMinds
        </a>

        <button class="menu-toggle">
            ☰
        </button>

        <div class="main-links">
            <a href="#">Home</a>
            <a href="#">Courses</a>
            <a href="#">Projects</a>
            <a href="#">About</a>
        </div>
    </nav>

    <section class="responsive-hero">
        <div class="hero-content">
            <span class="hero-badge">
                Responsive CSS
            </span>

            <h1>
                Build Websites for
                Every Screen
            </h1>

            <p>
                Create flexible layouts that
                adapt beautifully to phones,
                tablets, laptops, and desktops.
            </p>

            <div class="hero-actions">
                <button>
                    Start Learning
                </button>

                <button class="secondary">
                    View Courses
                </button>
            </div>
        </div>

        <div class="device-preview">
            <div class="desktop-device">
                <div class="device-header"></div>

                <div class="device-grid">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>

            <div class="mobile-device">
                <div class="mobile-screen">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>
        </div>
    </section>

    <section class="responsive-features">
        <article>
            <span>📱</span>

            <h3>Mobile</h3>

            <p>
                Single-column layouts with
                comfortable touch targets.
            </p>
        </article>

        <article>
            <span>📲</span>

            <h3>Tablet</h3>

            <p>
                Flexible multi-column layouts
                for medium screens.
            </p>
        </article>

        <article>
            <span>💻</span>

            <h3>Desktop</h3>

            <p>
                Spacious layouts that use
                available screen space.
            </p>
        </article>
    </section>
</div>
CSS
.responsive-page {
    width: min(
        100% - 32px,
        1200px
    );

    margin-inline: auto;
}

.main-nav {
    display: flex;

    align-items: center;

    justify-content:
        space-between;

    padding:
        18px 0;
}

.brand {
    color: #6c5ce7;

    font-size: 1.4rem;

    font-weight: 800;

    text-decoration: none;
}

.main-links {
    display: none;
}

.menu-toggle {
    display: block;

    padding:
        8px 12px;

    border: none;

    background: #6c5ce7;
    color: white;

    border-radius: 8px;
}

.responsive-hero {
    display: grid;

    grid-template-columns:
        1fr;

    gap: 50px;

    align-items: center;

    padding:
        60px 0;
}

.hero-badge {
    display: inline-block;

    padding:
        8px 16px;

    background:
        rgba(108, 92, 231, 0.12);

    color: #6c5ce7;

    border-radius: 999px;

    font-weight: 700;
}

.hero-content h1 {
    margin:
        20px 0;

    font-size:
        clamp(
            2.5rem,
            8vw,
            5rem
        );

    line-height: 1.05;
}

.hero-content p {
    max-width: 600px;

    color: #636e72;

    font-size: 1.1rem;

    line-height: 1.7;
}

.hero-actions {
    display: flex;

    flex-direction: column;

    gap: 12px;

    margin-top: 28px;
}

.hero-actions button {
    padding:
        14px 24px;

    border:
        2px solid #6c5ce7;

    background: #6c5ce7;
    color: white;

    border-radius: 10px;

    font-weight: 700;
}

.hero-actions .secondary {
    background: transparent;

    color: #6c5ce7;
}

.device-preview {
    position: relative;

    min-height: 320px;

    display: grid;

    place-items: center;
}

.desktop-device {
    width: min(
        100%,
        440px
    );

    padding: 12px;

    background: #2d3436;

    border-radius: 18px;
}

.device-header {
    height: 20px;

    margin-bottom: 12px;

    background: #636e72;

    border-radius: 6px;
}

.device-grid {
    display: grid;

    grid-template-columns:
        repeat(3, 1fr);

    gap: 10px;

    min-height: 180px;

    padding: 16px;

    background: white;

    border-radius: 10px;
}

.device-grid span {
    background:
        linear-gradient(
            135deg,
            #6c5ce7,
            #a29bfe
        );

    border-radius: 8px;
}

.mobile-device {
    position: absolute;

    right: 0;
    bottom: 0;

    width: 110px;

    padding: 8px;

    background: #2d3436;

    border-radius: 20px;
}

.mobile-screen {
    display: grid;

    gap: 8px;

    min-height: 190px;

    padding: 12px;

    background: white;

    border-radius: 14px;
}

.mobile-screen span {
    background: #00b894;

    border-radius: 6px;
}

.responsive-features {
    display: grid;

    grid-template-columns:
        1fr;

    gap: 20px;

    padding:
        40px 0 80px;
}

.responsive-features article {
    padding: 28px;

    background: #f5f6fa;

    border-radius: 16px;
}

.responsive-features article > span {
    font-size: 2.5rem;
}

@media (min-width: 600px) {
    .hero-actions {
        flex-direction: row;
    }

    .responsive-features {
        grid-template-columns:
            repeat(2, 1fr);
    }
}

@media (min-width: 768px) {
    .menu-toggle {
        display: none;
    }

    .main-links {
        display: flex;

        gap: 24px;
    }

    .main-links a {
        color: #2d3436;

        text-decoration: none;
    }
}

@media (min-width: 900px) {
    .responsive-hero {
        grid-template-columns:
            1.1fr 0.9fr;

        padding:
            100px 0;
    }

    .responsive-features {
        grid-template-columns:
            repeat(3, 1fr);
    }
}

@media (
    prefers-reduced-motion:
    no-preference
) {
    .device-preview {
        animation:
            floatDevice
            3s
            ease-in-out
            infinite
            alternate;
    }

    @keyframes floatDevice {
        to {
            transform:
                translateY(-15px);
        }
    }
}

Browser Processing Flow

Load HTML
Load CSS
Read Normal Rules
Find Media Queries
Check Current Environment
Evaluate Conditions
Apply Matching Rules
Resolve CSS Cascade
Render Layout
Media Query Processing
CSS Loaded
    │
    ▼
Normal Styles Applied
    │
    ▼
Media Query Found
    │
    ▼
Check Condition
    │
 ┌──┴──┐
 │     │
True  False
 │     │
 ▼     ▼
Apply  Ignore
Rules  Rules
 │
 ▼
Resolve Cascade
 │
 ▼
Render Responsive Page

Real-World Applications

Mobile Websites

Adapt desktop pages for narrow phone screens.

Navigation Menus

Switch between full navigation and mobile menu controls.

Content Layouts

Rearrange articles, sidebars, and related content.

E-Commerce

Adapt product grids and shopping interfaces.

Dashboards

Reorganize complex panels and data cards.

Print Styles

Remove navigation and unnecessary elements when printing.

Dark Mode

Respond to preferred system color schemes.

Accessibility

Reduce motion and adapt interaction behavior.

Advantages

Responsive Layouts

One website can support many screen sizes.

Better Usability

Layouts remain readable and usable on smaller devices.

Flexible Components

Components can rearrange according to available space.

Multiple Media Types

Styles can adapt for screens and printed pages.

Device Awareness

Interfaces can respond to hover and pointer capabilities.

User Preferences

CSS can respect color scheme and motion preferences.

Common Beginner Mistakes

Forgetting the Viewport Meta Tag

Mobile browsers may not use the expected viewport width without the correct viewport configuration.

Using Too Many Breakpoints

Excessive breakpoints make responsive CSS difficult to maintain.

Targeting Specific Phone Models

Breakpoints should usually respond to content needs rather than individual device names.

Mixing min-width and max-width Randomly

An inconsistent strategy can create confusing overlapping rules.

Wrong Media Query Order

The cascade can cause later matching rules to override earlier ones unexpectedly.

Forgetting CSS Units

Values such as 768 require a unit like px.

Using = Instead of :

Traditional media feature syntax uses a colon, such as max-width: 768px.

Missing Parentheses

Media feature conditions must use the correct parentheses.

Forgetting and Between Conditions

Multiple conditions require correct logical syntax.

Creating Fixed-Width Mobile Layouts

Large fixed widths can cause horizontal scrolling.

Hiding Important Content

Essential information should remain accessible on smaller screens.

Using Hover as the Only Interaction

Touch devices may not provide convenient hover behavior.

Tiny Touch Targets

Mobile controls should remain comfortable to tap.

Ignoring Landscape Mode

Short landscape viewports can expose layout problems.

Ignoring Viewport Height

A design can fit the width but still overflow vertically.

Testing Only One Device

Responsive layouts should be tested across many viewport sizes.

Using Device Width Instead of Content Needs

The layout should change when the content requires it.

Forgetting the Cascade

Media query rules still follow specificity and source order.

Overusing !important

Using !important to fix responsive conflicts often makes maintenance harder.

Ignoring User Preferences

Color scheme and motion preferences can improve accessibility and comfort.

Best Practices

  • Design layouts that work across a wide range of viewport sizes.
  • Use media queries when the layout genuinely needs to change.
  • Choose breakpoints according to content rather than device names.
  • Start with a consistent responsive strategy.
  • Consider mobile-first development for new responsive projects.
  • Use min-width queries consistently in mobile-first layouts.
  • Use max-width queries consistently in desktop-first layouts.
  • Avoid mixing responsive strategies without a clear reason.
  • Keep the number of breakpoints manageable.
  • Add breakpoints only when the content or layout requires them.
  • Test the layout between breakpoints, not only at exact breakpoint values.
  • Remember that media query styles follow the normal CSS cascade.
  • Place responsive overrides in a predictable order.
  • Watch for specificity conflicts.
  • Avoid unnecessary !important declarations.
  • Use flexible widths whenever possible.
  • Use max-width to prevent content from becoming excessively wide.
  • Use percentage widths for fluid elements.
  • Use CSS Grid and Flexbox for responsive layouts.
  • Change grid column counts according to available space.
  • Change flex-direction when horizontal space becomes limited.
  • Use gap for consistent spacing.
  • Avoid fixed widths that cause horizontal scrolling.
  • Make images responsive with max-width: 100%.
  • Keep image height proportional with height: auto.
  • Use responsive containers to control content width.
  • Keep text line lengths readable on wide screens.
  • Adjust typography when large headings become cramped.
  • Consider clamp() for fluid responsive typography.
  • Adjust padding and margins for smaller screens.
  • Avoid excessive empty space on mobile devices.
  • Keep touch targets comfortable to use.
  • Use pointer queries when interaction size depends on input accuracy.
  • Use hover queries for hover-specific enhancements.
  • Do not make essential functionality depend only on hover.
  • Test navigation on touch devices.
  • Use a compact navigation pattern when links no longer fit.
  • Do not hide essential navigation without providing an alternative.
  • Keep mobile menus keyboard accessible.
  • Test portrait and landscape orientations.
  • Use height queries when short viewports create problems.
  • Consider aspect ratio for media-heavy layouts.
  • Use print media queries when printed output matters.
  • Hide unnecessary interactive controls when printing.
  • Keep printed text readable.
  • Use prefers-color-scheme when automatic theme adaptation is useful.
  • Keep sufficient contrast in both light and dark modes.
  • Use prefers-reduced-motion for non-essential animation.
  • Preserve functionality when motion is removed.
  • Avoid unnecessary animation on small or low-powered devices.
  • Use logical operators carefully.
  • Remember that and requires every connected condition to match.
  • Remember that comma-separated queries work like OR.
  • Use not only when negating a media query is genuinely clearer.
  • Keep complex media queries readable across multiple lines.
  • Use comments when breakpoint purposes are not obvious.
  • Group related responsive rules logically.
  • Avoid repeating the same media query unnecessarily throughout small files.
  • Consider component organization in larger projects.
  • Do not create a breakpoint for every small visual difference.
  • Use responsive design together with flexible units.
  • Use rem for scalable typography and spacing.
  • Use percentages for fluid widths.
  • Use viewport units carefully.
  • Use min(), max(), and clamp() where they simplify responsive behavior.
  • Use auto-fit and minmax() when Grid can respond without explicit breakpoints.
  • Prefer CSS capabilities that reduce unnecessary media queries.
  • Test at very narrow widths.
  • Test at very wide widths.
  • Test browser zoom.
  • Test larger text settings.
  • Test content with longer words and labels.
  • Test navigation with additional menu items.
  • Test cards with different content lengths.
  • Test forms on small screens.
  • Test tables for horizontal overflow.
  • Test images and videos for overflow.
  • Use browser responsive design tools during development.
  • Also test on real devices when possible.
  • Do not assume browser tools perfectly reproduce every device behavior.
  • Check horizontal scrolling at every important width.
  • Use overflow carefully.
  • Avoid hiding overflow only to conceal layout bugs.
  • Keep source order logical.
  • Keep base styles simple.
  • Progressively enhance layouts as more space becomes available.
  • Use consistent breakpoint values across related components when appropriate.
  • Allow components to have independent responsive needs.
  • Avoid forcing every component to change at exactly the same breakpoint.
  • Keep media query conditions understandable.
  • Use modern range syntax when project browser support allows it.
  • Use traditional min-width and max-width syntax when broader compatibility is required.
  • Keep responsive CSS maintainable.
  • Create layouts that adapt naturally rather than only switching at fixed sizes.
  • Remember that responsive design includes more than screen width.
  • Consider height, orientation, pointer type, hover support, color scheme, and motion preferences.
  • Keep important content available on every device.
  • Prioritize readability and usability over matching a fixed screenshot.
  • Build responsive interfaces that remain functional at unexpected sizes.
Remember the Responsive Formula

Start with a flexible layout, identify where the content needs to change, add a breakpoint, and apply only the styles required for that new condition.

Frequently Asked Questions

What is a CSS media query?

A media query applies CSS styles only when specified environmental or viewport conditions are true.

What is responsive web design?

Responsive web design creates layouts that adapt to different screen sizes, devices, and viewing conditions.

What does @media do?

The @media rule creates a conditional block of CSS.

What is a breakpoint?

A breakpoint is a viewport size where the layout needs to change.

What does max-width mean?

It matches when the viewport is equal to or smaller than the specified width.

What does min-width mean?

It matches when the viewport is equal to or larger than the specified width.

What is mobile-first design?

Mobile-first design starts with small-screen styles and adds enhancements for larger screens.

Which queries are common in mobile-first design?

Mobile-first designs commonly use min-width media queries.

What is desktop-first design?

Desktop-first design starts with large-screen styles and simplifies them for smaller screens.

Which queries are common in desktop-first design?

Desktop-first designs commonly use max-width media queries.

Should I use mobile-first or desktop-first?

Either can work, but a consistent strategy is important. Mobile-first is commonly used for modern responsive development.

What are common breakpoint sizes?

Values such as 576px, 768px, 992px, and 1200px are common examples, but breakpoints should be based on the actual content and layout.

Should I create breakpoints for specific phones?

Usually no. Create breakpoints when the content needs a layout change.

Can media queries check height?

Yes. Features such as min-height and max-height can respond to viewport height.

Can media queries detect orientation?

Yes. The orientation feature can check for portrait or landscape layouts.

Can media queries detect dark mode?

Yes. Use prefers-color-scheme.

Can media queries detect reduced motion preferences?

Yes. Use prefers-reduced-motion.

Can media queries detect hover support?

Yes. Use the hover media feature.

Can media queries detect touch-like input?

The pointer media feature can identify coarse and fine primary pointers.

What does and do in a media query?

It combines conditions and requires all connected conditions to match.

What does a comma do in media queries?

A comma separates alternative queries and works like an OR condition.

Do media queries override normal CSS?

They participate in the normal CSS cascade. Specificity and source order still apply.

Can I use media queries with Flexbox?

Yes. You can change flex direction, wrapping, alignment, and other properties.

Can I use media queries with Grid?

Yes. You can change column counts, rows, gaps, and layout structure.

Can I hide elements with media queries?

Yes, but essential content should remain accessible through an appropriate responsive alternative.

How do I make images responsive?

A common approach is max-width: 100% and height: auto.

Do I always need media queries for responsive layouts?

No. Flexible units, Flexbox, Grid, auto-fit, minmax(), min(), max(), and clamp() can create responsive behavior without explicit breakpoints.

Can media queries be nested inside selectors?

Traditional CSS commonly places @media rules at the stylesheet level, while modern CSS nesting support can allow additional organizational patterns depending on browser support.

What media type is used for printed pages?

Use the print media type.

What is modern media query range syntax?

It uses comparison operators such as width >= 768px or 600px <= width <= 900px.

What comes after CSS Media Queries?

The next lesson covers CSS Variables, including custom properties, the var() function, fallback values, scope, inheritance, themes, calculations, JavaScript integration, and practical examples.

Key Takeaways

  • Media queries apply CSS when specified conditions are true.
  • Responsive design adapts websites to different screens and devices.
  • The @media rule creates conditional CSS.
  • max-width targets widths equal to or smaller than a value.
  • min-width targets widths equal to or larger than a value.
  • A breakpoint is a width where the layout needs to change.
  • Breakpoints should be based on content needs.
  • Mobile-first design commonly uses min-width queries.
  • Desktop-first design commonly uses max-width queries.
  • Media queries can respond to width and height.
  • Orientation queries detect portrait and landscape layouts.
  • Hover queries detect hover capability.
  • Pointer queries detect pointer accuracy.
  • prefers-color-scheme can detect light and dark preferences.
  • prefers-reduced-motion can reduce non-essential animation.
  • The and operator combines required conditions.
  • Comma-separated media queries work like OR.
  • Media queries work with the normal CSS cascade.
  • Flexbox and Grid can change layouts at breakpoints.
  • Responsive design should preserve important content.
  • Flexible layouts can reduce the number of media queries required.
  • Responsive websites should be tested between breakpoints and on real devices.

Summary

CSS Media Queries allow styles to respond to viewport dimensions, device capabilities, media types, and user preferences.

Responsive Web Design uses flexible layouts and conditional styles to create websites that work across phones, tablets, laptops, and desktop screens.

The @media rule contains CSS that is applied only when its conditions match.

The max-width feature commonly targets smaller viewports, while min-width commonly targets larger viewports.

A breakpoint is a point where the layout needs to change because the current design no longer works comfortably.

Mobile-first design begins with small-screen styles and adds enhancements using min-width queries.

Desktop-first design begins with large-screen styles and simplifies layouts using max-width queries.

Media queries can change typography, navigation, spacing, Flexbox layouts, Grid layouts, images, and component visibility.

The orientation media feature can distinguish between portrait and landscape viewports.

The hover and pointer features can adapt interfaces according to input capabilities.

The prefers-color-scheme feature can respond to light and dark mode preferences.

The prefers-reduced-motion feature can reduce or remove non-essential animations.

Logical operators can combine, negate, or provide alternative media query conditions.

Responsive design should use flexible layouts first and add breakpoints only when the content requires them.

In the next and final CSS lesson, you will learn CSS Variables, including custom properties, the var() function, fallback values, scope, inheritance, reusable design values, themes, calculations, and JavaScript integration.