0
0
Astroframework~30 mins

client:media for responsive interactivity in Astro - Mini Project: Build & Apply

Choose your learning style9 modes available
Responsive Image Gallery with client:media in Astro
📖 Scenario: You are building a simple image gallery for a website. The gallery should show different images depending on the screen size. This helps users see the best version of images on their device, whether a phone, tablet, or desktop.
🎯 Goal: Create an Astro component that uses client:media to load different images based on screen width. The gallery will show a small image on narrow screens and a larger image on wider screens.
📋 What You'll Learn
Create an Astro component with an image element
Add a media query variable to detect screen width
Use client:media with the media query to load images responsively
Ensure the component updates images automatically when resizing the browser
💡 Why This Matters
🌍 Real World
Responsive images improve website performance and user experience by loading appropriate images for different devices.
💼 Career
Knowing how to use client:media in Astro is useful for frontend developers building fast, adaptive websites.
Progress0 / 4 steps
1
Set up the image URLs
Create two variables called smallImage and largeImage with these exact string values: "/images/small.jpg" and "/images/large.jpg" respectively.
Astro
Hint

Use const to create variables and assign the exact string paths.

2
Define the media query
Create a variable called mediaQuery and set it to the string "(min-width: 600px)" to detect screens wider than 600 pixels.
Astro
Hint

Use const mediaQuery = "(min-width: 600px)" exactly.

3
Add the responsive image element
Write an <img> element that uses client:media={mediaQuery}. Set the default src attribute to {smallImage} and add client:media={mediaQuery} src={largeImage} after the directive.
Astro
Hint

Use <img src={smallImage} client:media={mediaQuery} src={largeImage} alt="Responsive gallery image" />.

4
Complete the Astro component
Wrap the code in an <Fragment> or root element if needed. Ensure the component exports properly and includes the image with client:media for responsive interactivity.
Astro
Hint

Use Astro frontmatter with --- and wrap the image in <> fragment tags.