0
0
Astroframework~5 mins

client:media for responsive interactivity in Astro

Choose your learning style9 modes available
Introduction

client:media helps your website react to screen size changes. It makes your site interactive only when needed, saving resources.

Show a mobile menu only on small screens.
Load a slideshow only on large screens.
Change button styles based on device width.
Hide heavy animations on small devices to improve speed.
Syntax
Astro
<Component client:media="(media-query)"></Component>

Replace (media-query) with a CSS media query like (max-width: 600px).

The component inside loads only if the media query matches the current screen.

Examples
This loads the MobileMenu component only on screens 600px wide or smaller.
Astro
<MobileMenu client:media="(max-width: 600px)" />
This loads the DesktopGallery component only on screens 1024px wide or larger.
Astro
<DesktopGallery client:media="(min-width: 1024px)" />
This loads the Sidebar component only on medium-sized screens between 768px and 1200px.
Astro
<Sidebar client:media="(min-width: 768px) and (max-width: 1200px)" />
Sample Program

This example shows a header that loads a mobile menu on small screens and a desktop menu on larger screens. Only one menu loads depending on the screen size, improving performance and user experience.

Astro
---
import MobileMenu from '../components/MobileMenu.astro';
import DesktopMenu from '../components/DesktopMenu.astro';
---

<header>
  <MobileMenu client:media="(max-width: 600px)" />
  <DesktopMenu client:media="(min-width: 601px)" />
</header>
OutputSuccess
Important Notes

client:media uses standard CSS media queries, so you can reuse what you know from CSS.

It helps reduce unnecessary JavaScript loading on devices that don't need it.

Test your media queries in browser DevTools by resizing the window to see the effect.

Summary

client:media loads components only when a media query matches.

It improves performance by avoiding loading unneeded code on certain screen sizes.

Use it to make your site responsive and interactive in a smart way.