Modal opening causes layout shift - debugging CSS issue

2 replies
Last updated: Mar 19, 2024
wondering if anyone knows what’s causing this shift when a modal is opened. At first i thought it was Tailwind’s preflight but I disabled that and and it still occurs. I thought my css debugging skills were good but this is putting me to the test.
AI Update

This is a classic CSS issue that happens when modals open - it's almost certainly caused by the scrollbar disappearing, not something specific to Sanity Studio or Tailwind.

What's happening:

When a modal opens, it typically sets overflow: hidden on the body to prevent background scrolling. This removes the scrollbar, causing the content to shift horizontally by the scrollbar width (usually 15-17px). It's jarring because the content suddenly jumps to fill that space.

Quick fix - Force scrollbar to always show:

body {
  overflow-y: scroll;
}

This keeps the scrollbar visible even when content doesn't overflow, preventing the shift. The downside is you'll always see a scrollbar (though it'll be grayed out when not needed).

Better fix - Compensate with padding:

Calculate the scrollbar width and add padding when the modal opens:

// When modal opens
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.paddingRight = `${scrollbarWidth}px`;
document.body.style.overflow = 'hidden';

// When modal closes
document.body.style.paddingRight = '';
document.body.style.overflow = '';

Many modal libraries handle this automatically, but if you're building custom modals or if Sanity Studio's dialogs are causing this, you might need to implement it yourself.

If this is happening with Studio's built-in dialogs and you have custom global CSS, check if you're overriding any of Studio's default modal/body styles - that could interfere with how it manages scroll locking.

Show original thread
2 replies
Looks like you’re embedding your Studio in an Astro frontend. What does your code look like for that?
Ya I was indeed embedding in Astro. I’m starting to understand that embedding almost always causes conflicts and am just separating for the time being. Resolved it when it stand alone.

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?