Search code examples
htmlcsscss-positiontailwind-cssabsolute

Fix Element at Bottom of the Screen, but only as long as the Parent Container hasn't ended?


Say I have an element that is visually part of a container. This container can be very long in height.

Now when the user scrolls down, I want to position this element to remain at the bottom of the screen. But when the container ends at some point, I want the element to stay at the bottom of that container and no scroll down further.

So once again: When the container hasn't ended yet, the element is at the bottom of the screen:

enter image description here

... but when I continue scrolling, it stops inside the container:

enter image description here

I am a bit stuck here. I do know how to do this when the element is positioned at the top inside of the container. Scrolling down will then just make it stop at the bottom.

The problem seems to be that either the Element will be moved outside of the document flow, so it won't remain inside the container, OR it will be at the bottom of the container all the time, so the element won't scroll with the user and remain on the bottom of the screen.

Any ideas?

<div className="mx-20 my-36">
    <div className="bg-slate-200 h-[1200px] w-full relative border-2 border-black relative">
        <div className="fixed bottom-0 left-0 right-0 p-2 bg-white w-full border-2 border-red-600">Element</div>
    </div>

    <div className="my-12">

        The page continues here but the element remains in the container ...
    </div>
</div>

PS: Using tailwind & react here, but any vanilla CSS are welcome too! I would love to solve this without javascript.


Solution

    1. Create a parent div around both elements. Move all styles to this parent except for the height.
    2. Switch out fixed for sticky
    3. You can remove relative - it doesn't do anything anymore
    <div className="mx-20 my-36">
      <div className="bg-slate-200 border-2 border-black w-full">
        <div className="h-[1200px]">
        </div>
        <div className="sticky bottom-0 left-0 right-0 p-2 bg-white w-full border-2 border-red-600">Element</div>
      </div>
    
      <div className="my-12">
        The page continues here but the element remains in the container ...
      </div>
    </div>
    

    DEMO: https://play.tailwindcss.com/gy71xPcjnR