kjdion84
kjdion84

Reputation: 10064

Stop element underneath fixed overlay from scrolling with Tailwind

I'm trying to create an overlay that may contain its own scrollbar. The overlay should take up the full width and height of the screen, and scroll its own contents if they are longer than the page height.

My problem is I can't figure out how to stop the actual page from scrolling when the overlay scrolls. I want this to act like a Bootstrap modal.

Here is the fiddle with a code example: https://jsfiddle.net/r5jLcekb/

In the example, I'm using:

fixed bg-black bg-opacity-50 w-screen h-screen overflow-y-scroll

As you can see, the page scrolls it's contents, not just the overlay. I only want the contents within the overlay to scroll. Is this possible to do purely with tailwind?

Upvotes: 2

Views: 25550

Answers (5)

Shane Stratton
Shane Stratton

Reputation: 61

You can do this in Tailwind by:

  • designating a class in your root styles file (e.g. /styles/globals.css) to remove overflow from :root
  • conditionally apply that class to whatever overlay you're using, when it's open

For example, in my NextJS project, I added:

 :root:has(.no-doc-scroll) {
    overflow:hidden;
  }

to /styles/globals.css and then I added this class to my full screen overlay with:

{isOpen && (<div className={"h-screen w-screen fixed top-0 left-0 z-50 no-doc-scroll"}>
...
)}

DaisyUI does this for their modals.

Upvotes: 5

Otter
Otter

Reputation: 419

You can use overscroll-contain in combination with overflow-scroll,overflow-x-scroll, or overflow-y-scroll, which blocks the parent from scrolling at the same time. 🤘

Ref: https://tailwindcss.com/docs/overscroll-behavior

Upvotes: 1

JoCJo
JoCJo

Reputation: 1

I had this same issue. My parent container was scrolling for the entire length of the site when the fullscreen overlay was active, but the content was not scrolling in the fullscreen overlay. I added overflow-y-scroll and overscroll-y-none to the fixed container and it worked nicely. Hope this saves someone some time :) Thanks Jas (comment above) for the point to overscroll.

See https://tailwindcss.com/docs/overflow and https://tailwindcss.com/docs/overscroll-behavior

Upvotes: 0

Besufekad Tamiru
Besufekad Tamiru

Reputation: 126

The way I approached this problem is by adding a class to the body whenever this overlay is rendered. Whenever your overlay element is mounted you need to execute a javascript code that does the following :

  document.body.classList.add(`overflow-hidden`);
    document.body.style.marginRight =
      document.body.offsetWidth - widthBefore + "px";

The second assignment is optional and it's added to get rid of layout shift when scrollbar shows and hides

Upvotes: 1

Jas
Jas

Reputation: 27

I think you're looking for overscroll-auto -- see https://tailwindcss.com/docs/overscroll-behavior for more.

Upvotes: -1

Related Questions