How to Autosize an Image within a Div and Resize for Screen Changes
When working with Sanity image URLs, you can create responsive images that auto-resize based on screen size by combining several URL parameters. Here's how to approach this:
Basic Responsive Strategy
The key is using the fit parameter along with width/height constraints. For an image that automatically sizes to fit within a parent div's bounding box, use:
?fit=max&w=[maxWidth]&h=[maxHeight]
The fit=max option ensures the image fits within the box you specify without ever scaling up beyond its original dimensions. This prevents small images from becoming pixelated.
Other Useful fit Options
fit=clip- Resizes to fit within bounds without cropping or distortingfit=fill- Fits within bounds and fills empty space with a background color (use with&bg=parameter)fit=crop- Crops the image to fill the specified dimensions exactly
Responsive Implementation Example
For responsive images across different screen sizes, you'd typically:
- Use CSS to make the image responsive (
width: 100%; height: auto;) - Generate multiple image URLs at different sizes using Sanity's URL parameters
- Use
srcsetor<picture>elements to serve appropriate sizes
<img
src="https://cdn.sanity.io/images/project/dataset/image-id.jpg?w=800&fit=max"
srcset="
https://cdn.sanity.io/images/project/dataset/image-id.jpg?w=400&fit=max 400w,
https://cdn.sanity.io/images/project/dataset/image-id.jpg?w=800&fit=max 800w,
https://cdn.sanity.io/images/project/dataset/image-id.jpg?w=1200&fit=max 1200w
"
sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
style="width: 100%; height: auto;"
alt="Description"
/>Additional Tips
- Auto-format: Add
?auto=formatto automatically serve the most optimized format (WebP, AVIF) based on browser support - Quality: Use
&q=75to balance quality and file size (default is 75 for JPG/WebP) - Always use integers: Non-integer values for
wandhcan cause performance issues
Helper Library
Consider using the @sanity/image-url helper library, which makes it easier to generate these URLs programmatically with proper parameters for responsive images.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.