loading...
Cover image for Fit Your UI to the Screen on Mobile Browsers

Fit Your UI to the Screen on Mobile Browsers

ozanbolel profile image Ozan Bolel ・2 min read

Fitting your UI to the screen on mobile devices gets weird sometimes. Most mobile browsers have navigation bars or applications menus that hide itself while user is scrolling down throughout the page. This causes the actual height of the window to change. What difference does it make? Let's say you want your footer to be fixed at the bottom of every page. Without a proper fix, it won't work. Here is the difference:

Alt Text

I know my drawing is bad, but I hope you got the idea. This is even more important when working with modals on mobile:

Alt Text

If you can't fit your modals to the screen, users won't see some parts of your UI. Maybe they will miss some important buttons. How to fix this? Well, it's very easy.

1. Add The Viewport Metatag

<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">

I know this is Responsive 101, but begginners tend to forget about this. So, just in case...

2. Set CSS Variable

  const resizeOps = () => {
    document.documentElement.style.setProperty("--vh", window.innerHeight * 0.01 + "px");
  };

  resizeOps();
  window.addEventListener("resize", resizeOps);

This block should run as soon as your app starts. It will set 1% of the actual view height of the window as a CSS variable whenever the window resizes. We'll use this variable in the next and the last step.

3. Adjust Your CSS

html, body {
  height: 100vh;
  height: calc(var(--vh, 1vh) * 100);
}

First height property is for older browser in case if the browser doesn't support CSS variables. You can see its support table here. If you don't want your whole page to behave in this way, you can also do something like this:

.modal {
  width: 50vw;
  height: 50vh;
  height: calc(var(--vh, 1vh) * 50);
}

In short; for individual UI elements, all you need to do is using calc(var(--vh, 1vh) * 50) instead of 50vh.


I hope this was useful, you can also follow me on Twitter for future content:

twitter.com/oznbll

Posted on by:

ozanbolel profile

Ozan Bolel

@ozanbolel

Self-taught frontend developer. Music lover.

Discussion

markdown guide