What are the Best CSS attributes to Achieve the Hotspot from Sanity Image?

3 replies
Last updated: May 30, 2020
Hey Team it's a dumb doubt but what best CSS attributes we have to use to achieve the hotspot from Sanity Image
AI Update

Not a dumb question at all! The hotspot feature is super useful but the CSS implementation isn't always obvious.

When Sanity stores hotspot data, it gives you x and y values between 0 and 1 (representing 0-100% from the left/top edges). The key CSS attributes to use are:

For <img> tags or Next.js Image components:

Use object-position along with object-fit: cover:

function getPositionFromHotspot(hotspot) {
  if (!hotspot?.x || !hotspot?.y) return "center";
  
  return `${hotspot.x * 100}% ${hotspot.y * 100}%`;
}

// Usage
<img 
  src={imageUrl}
  style={{
    objectFit: 'cover',
    objectPosition: getPositionFromHotspot(image.hotspot)
  }}
/>

// Or with Next.js Image
<Image
  src={imageUrl}
  fill
  style={{
    objectFit: 'cover',
    objectPosition: getPositionFromHotspot(image.hotspot)
  }}
/>

For background images:

Use background-position along with background-size: cover:

<div style={{
  backgroundImage: `url(${imageUrl})`,
  backgroundSize: 'cover',
  backgroundPosition: `${hotspot.x * 100}% ${hotspot.y * 100}%`
}} />

The key conversion:

  • Sanity's hotspot.x: 0.5 → CSS: 50% (horizontal center)
  • Sanity's hotspot.y: 0.3 → CSS: 30% (30% from top)

The Sanity image hotspot documentation covers enabling hotspot in your schema, and there's a helpful community answer about using hotspot with Next.js that shows this CSS approach is often necessary because the Image URL Builder doesn't always automatically apply hotspot positioning in all frameworks.

I would recommend using the image-url builder when using hotspot. Just give it the asset, including the hotspot and cropping data and it will generate the url for you. You don't have to do any css trickery unless you have a special needs.

https://www.sanity.io/docs/image-url
Thanks
user J
will work on it!
It worked thanks !

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.

Was this answer helpful?