📊 5. Tables and Layout
Estimated reading: 9 minutes 3 views

📱 HTML: Media Queries and Container Queries (with CSS)

In today’s multi-device world, creating responsive web layouts that adapt to different screen sizes and device capabilities is essential. Media queries and container queries are powerful CSS techniques that enable developers to create truly responsive designs. This comprehensive guide explores both query types, their syntax, use cases, and implementation strategies to help you build flexible, device-agnostic web experiences.


🔹 Understanding Media Queries

Media queries are a fundamental CSS technique introduced in CSS3 that allows you to apply different styles based on device characteristics or browser viewport conditions. They provide the foundation for responsive web design by enabling conditional styling based on specific criteria.

💡 What Are Media Queries?

Media queries use the @media rule to include CSS properties only when certain conditions are true. They act as conditional statements that check various aspects of the user’s device or browser and apply specific styles when those conditions are met. For example, you can create different layouts for mobile phones, tablets, and desktop computers all within the same stylesheet. Media queries have been the backbone of responsive design for many years, allowing websites to adapt to different screen sizes and device capabilities.

🎨 Media Query Syntax

The basic media query syntax follows this pattern:

@media media-type and (media-feature-rule) {
/* CSS rules to apply when conditions match */
}

This structure consists of three key components: an optional media type that specifies the category of device, a media expression that defines the rule or test, and the CSS rules that will be applied if the test passes. The media type is optional when not using the only logical operator, with all being the default if not specified.

📱 Media Types Explained

Media types tell the browser what kind of media the code is intended for. The commonly used media types include:

  • all: Suitable for all devices (default)
  • print: For printed material and documents in print preview mode
  • screen: Intended primarily for computer screens, tablets, and smartphones

⭐ Pro Tip: Other media types like ttytvprojectionhandheldbraille, and embossed have been deprecated in modern specifications and should be avoided.


🔹 Implementing Media Queries

Media queries can be implemented in several ways within your HTML and CSS files, giving you flexibility in how you structure your responsive designs.

💡 Using Media Queries in Stylesheets

The most common way to use media queries is directly within your CSS file using the @media rule. This approach allows you to group all your responsive styles together with your base styles:

/* Base styles for all devices */
body {
font-family: Arial, sans-serif;
}

/* Styles for smaller screens */
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}

In this example, the background color will change to light blue only when the viewport width is 600px or smaller.

🛠️ Media Queries in HTML

You can also specify media queries directly in your HTML using the media attribute with <link> elements. This approach lets you load entirely different stylesheets based on the device characteristics:

xml<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen and (max-width: 600px)">

This method can improve performance as browsers will download stylesheets with lower priority if their media queries don’t match the current device.

📝 Note:

When using the media attribute, you can combine multiple conditions using logical operators like andnot, and , (comma for OR operations). For example, media="screen and (min-width: 768px) and (max-width: 1024px)" would target medium-sized screens like tablets.


🔹 Media Features and Breakpoints

Media features allow you to test specific characteristics of the user’s device or browser. They form the foundation of responsive design breakpoints.

💡 Common Media Features

The most frequently used media features include:

  • width: Tests the width of the viewport
  • height: Tests the height of the viewport
  • orientation: Checks if the device is in landscape or portrait mode
  • resolution: Tests the pixel density of the display
  • aspect-ratio: Examines the width-to-height ratio of the viewport
  • hover: Detects if the device supports hover interactions
  • prefers-color-scheme: Determines if the user prefers light or dark mode

🎨 Using Min and Max Prefixes

You can use the min- and max- prefixes with many media features to create ranges:

css/* Applies to screens between 768px and 1024px wide */
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* Tablet-specific styles */
}

Alternatively, you can use the newer range syntax for more concise code:

css@media (768px <= width <= 1024px) {
/* Tablet-specific styles */
}

Both approaches are equivalent, though the range syntax has slightly less browser support14.

⭐ Common Breakpoints

While breakpoints should ideally be based on your content rather than specific devices, these common breakpoints can serve as a starting point:

  • Mobile: max-width: 600px
  • Tablet: min-width: 601px and max-width: 1024px
  • Desktop: min-width: 1025px.

🔹 Container Queries: The Next Evolution

Container queries represent a significant advancement in responsive design, allowing elements to respond to their parent container’s size rather than just the viewport size.

💡 What Are Container Queries?

Container queries enable you to apply styles to an element based on its container’s size, styles, or scroll state. They provide a more modular approach to responsive design compared to media queries, which only respond to viewport dimensions4. This means you can create truly reusable components that adapt based on where they’re placed in the layout, not just the overall screen size.

🛠️ Container Query Syntax

The basic syntax for container queries involves two steps:

  1. Define a containment context using the container-type property:
css.container {
  container-type: inline-size;
}
  1. Create a container query using the @container rule:
@container (min-width: 400px) {
.card {
display: flex;
}
}

In this example, the .card element will switch to a flex layout when its nearest container with container-type is at least 400px wide.

📝 Container Types

You can use different container types depending on what dimensions you want to query:

  • size: Queries both inline and block dimensions of the container
  • inline-size: Queries only the inline dimension (width in horizontal writing modes)
  • normal: Used for container style queries rather than size queries

🔹 Container Query Units

Container queries introduce new relative units that reference the container’s dimensions rather than the viewport.

💡 Understanding Container Query Units

Container query units allow you to size elements relative to their container dimensions. These include:

  • cqw: 1% of a container’s width
  • cqh: 1% of a container’s height
  • cqi: 1% of a container’s inline size
  • cqb: 1% of a container’s block size
  • cqmin: The smaller value between cqi and cqb
  • cqmax: The larger value between cqi and cqb5

These units make it possible to create truly modular components that scale proportionally to their containers.

⭐ Pro Tip:

Container query units work even if you don’t have a container query in your CSS. As long as an element is inside a containment context, you can use these units to create proportional sizing5.

.container {
container-type: inline-size;
}

.container h2 {
font-size: 5cqi; /* 5% of the container's inline size */
}

🔹 Media Queries vs. Container Queries

Understanding when to use each query type is crucial for creating efficient responsive designs.

💡 When to Use Media Queries

Media queries remain the best choice for:

  • Page-level layout changes based on viewport size
  • Adapting to device capabilities like touch support or color schemes
  • Print styles and other media-specific adaptations
  • Broad layout shifts like changing a sidebar to a top navigation on mobile

🎨 When to Use Container Queries

Container queries excel at:

  • Component-level responsiveness that’s independent of viewport size
  • Creating truly reusable UI components that adapt to their context
  • Nested layouts where the same component might appear in different-sized containers
  • Cards, widgets, and other modular elements that need to be flexible4

📝 Note:

The two technologies are complementary rather than competitive. Media queries handle macro-level layout concerns, while container queries manage micro-level component adaptations. Using them together provides the most flexible approach to responsive design.


🔹 Browser Support and Fallbacks

Understanding browser support is crucial when implementing these technologies in production environments.

💡 Media Query Support

Media queries have excellent browser support across all modern browsers. Even older versions of Internet Explorer (from IE9 onwards) support basic media query functionality. The newer range syntax (min-width: 400px and 400px <= width) has slightly less support in older browsers, so consider using the traditional syntax for maximum compatibility.

🛠️ Container Query Support

Container queries are newer and have less widespread support. As of early 2025, container queries are supported in:

  • Chrome (from version 105)
  • Firefox (from version 110)
  • Safari (from version 16)
  • Edge (from version 105)

For browsers that don’t support container queries, you should provide sensible fallbacks using feature detection.

⭐ Pro Tip: Feature Detection

You can use @supports to detect container query support:

/* Default styles for all browsers */
.card {
display: block;
}

/* Styles for browsers that support container queries */
@supports (container-type: inline-size) {
.container {
container-type: inline-size;
}

@container (min-width: 400px) {
.card {
display: flex;
}
}
}

❓ Frequently Asked Questions

❓ What’s the difference between media queries and container queries?

👉 Media queries respond to the viewport’s characteristics (like screen width or device capabilities), while container queries respond to the size or properties of a specific container element. Media queries are viewport-centric, while container queries are component-centric.

❓ Can I use both media queries and container queries together?

👉 Absolutely! In fact, it’s recommended to use both for comprehensive responsive designs. Media queries handle page-level layouts and device adaptations, while container queries make individual components responsive to their immediate context.

❓ Do container queries impact performance?

👉 Container queries do have some performance cost since the browser needs to track container sizes and recalculate styles when containers resize. However, modern browsers have optimized this process, and the performance impact is usually minimal compared to the benefits they provide for responsive design.

❓ How do I target high-resolution (Retina) displays with media queries?

👉 You can use the resolution media feature to target high-DPI displays:
@media (min-resolution: 2dppx) {
/* Styles for high-resolution displays */
}

❓ Can I use media queries with the picture element for responsive images?

👉 Yes! The <picture> element combined with <source> elements that use the media attribute is perfect for responsive images. This allows you to serve different image files based on screen size910:
<picture>
<source media="(min-width: 650px)" srcset="large-image.jpg">
<source media="(min-width: 465px)" srcset="medium-image.jpg">
<img src="small-image.jpg" alt="Responsive image">
</picture>


Leave a Reply

Your email address will not be published. Required fields are marked *

Share this Doc

📱 HTML: Media Queries and Container Queries (with CSS)

Or copy link

CONTENTS
Scroll to Top