DEV Community

Cover image for 🔍 How stick element to bottom of viewport on mobile
Vladimir Schneider
Vladimir Schneider

Posted on

🔍 How stick element to bottom of viewport on mobile

Hi there 👋🏼

Not so long ago I had a task – to fix position the button on the viewport bottom. I spent some time in Figma to draw very beautiful button to stick to bottom of viewport.

In the moment I wrote this

.beautiful-button {
    position: fixed;
    bottom: 0;
}
Enter fullscreen mode Exit fullscreen mode

And...it worked!

I was happy of solved task and went to do another. Everything was fine until I insert field. When I click in and I saw keyboard and...my button disappeared. I was so sad.

So, maybe the problem is in the safe area? I try this

.beautiful-button {
    position: fixed;
    bottom: 0;
    bottom: calc(0 + env(safe-area-inset-bottom));
}
Enter fullscreen mode Exit fullscreen mode

and this doesn't work too.

I thought that Safari is Safari and go research next.

The first solution that came to mind was calculate the height of the viewport

const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
Enter fullscreen mode Exit fullscreen mode

and this doesn't work. Viewport height with keyboard and without is equal.

After googling and colleagues asking I knew about Visual Viewport API (https://developer.mozilla.org/en-US/docs/Web/API/Visual_Viewport_API).

Turns out there is an API to get viewport size.

The visual viewport is the visual portion of a screen excluding on-screen keyboards, areas outside of a pinch-zoom area, or any other on-screen artifact that doesn't scale with the dimensions of a page. (MDN).

So, my solution will be to use this

window.visualViewport.height
Enter fullscreen mode Exit fullscreen mode

You can use window.visualViewport to listen events

window.visualViewport.addEventListener('resize', resizeHandler);
window.visualViewport.addEventListener('scroll', scrollHandler);
Enter fullscreen mode Exit fullscreen mode

And use e.target to get viewport's parameters.

That's all! My beautiful button is now in the position it should be.

Thank you for reading ❤️

Top comments (0)