SanityImage outputs a single <img> tag with no wrapper elements, you have complete control over styling. This guide covers best practices for making your images responsive and handling common layout patterns.
Recommended Base Styles
Set these CSS rules globally for images in your project to ensure they behave as responsive, block-level elements:What This Does
display: block- Removes the inline spacing below imagesmax-width: 100%- Prevents images from overflowing their containerwidth: 100%- Makes images fill their container widthheight: auto- Maintains aspect ratio even withwidthandheightattributes set
These styles ensure images are infinitely scalable within their containers, even though
SanityImage sets explicit width and height attributes to prevent layout shifts.Responsive Grid Example
Here’s how to create a 3-column responsive grid where images scale with the viewport:How It Works
- The grid has a maximum width of 1,240px with 20px padding on each side
- Each column is approximately 390px at maximum width
- The
sizesattribute tells the browser the actual rendered size:- At 1240px and above: each image is exactly 390px
- Below 1240px: each image is
(viewport width - 40px padding - 30px gap) / 3
- With the base CSS above, images automatically scale down on smaller screens
Uniform Height Grid
To create a grid where all images have the same height, usecover mode:
Object Fit for Fine Control
Whilemode="cover" controls how Sanity crops the image, CSS object-fit controls how the browser displays it:
Object Fit Values
cover- Fills the container, cropping if necessary (similar tomode="cover")contain- Fits within the container, letterboxing if necessaryfill- Stretches to fill the container (may distort)none- Displays at original sizescale-down- Uses the smallest ofnoneorcontain
The sizes Attribute
The sizes attribute is crucial for responsive images. It tells the browser what size the image will be rendered at different viewport widths:
- At 1200px and above: image is 800px wide
- Between 768px and 1200px: image is 50% of viewport width
- Below 768px: image is 100% of viewport width
Common Layout Patterns
Full-Width Hero Image
Sidebar Thumbnail
Constrained Content Image
Styling with CSS-in-JS
SanityImage works seamlessly with CSS-in-JS libraries like Emotion:Preventing Layout Shift
SanityImage automatically sets width and height attributes based on the computed output dimensions. Combined with the recommended CSS, this prevents layout shift during page load:
height: auto CSS rule allows the height to scale proportionally, while the attributes prevent the browser from reserving no space before the image loads.
Next Steps
Cover vs Contain
Understand when to use each mode
Background Images
Use SanityImage for background images