I'm currently working on a CSS layout where I have a fixed parent div containing another div. I want the inner div to be fixed relative to the body, not its parent.
Code (Tailwind):
<div class="h-screen bg-red-100">
<div class="fixed left-1/2 top-1/2 h-80 w-80 -translate-x-1/2 -translate-y-1/2 bg-red-300">
<div class="fixed top-10 h-40 w-40 bg-red-600">I want to make this div fixed relative to body</div>
</div>
</div>
Is there a way to achieve this without JavaScript? If not, how can I accomplish it using JavaScript?
I've also researched extensively and searched on Stack Overflow, but I couldn't find a solution that fits my exact requirements.
Thank you!
More Info:
Based on @Paulie_D and @Yogi 's replies, I checked once again in my code. If I am using any translate property in my code, then I found out that it's for modal opening and closing transition
(opening from top to down and closing from down to top). I have added the translate property for this purpose.
<div
role="dialog"
aria-modal="true"
tabIndex="-1"
onKeyDown={handleTabKey}
ref={modalRef}
className={`fixed top-0 left-0 inset-0 flex justify-center items-center bg-black z-50 bg-opacity-50 backdrop-blur-sm ${
isModalOpen ? "opacity-100" : "opacity-0 pointer-events-none"
} transition-all ease-in-out`}
>
<div
className={`bg-white rounded-md w-[30%] p-3 tb:p-6 ${
isModalOpen ? "translate-y-0" : "-translate-y-full"
} transition-all ease-in-out`}
>
. . . .
</div>
</div>
Now I am going to remove it, but please, can anyone help me with how we can achieve the same transition without the translate property?
Finally, I found the solution:
Initially, I was using the translate property for my modal transition (top to bottom).
I discovered that a fixed div is always relative to the body. However, if there is any translate property applied to its parent, it cannot extend beyond that parent div.
To resolve this, I removed the translate property. Instead, for the modal transition effect, I added the class relative ${isOpen ? "top-0" : "-top-full"}. This approach worked perfectly.
Thanks to all.