DEV Community

Cover image for Fit Your UI to the Screen on Mobile Browsers
Ozan Bolel
Ozan Bolel

Posted on

Fit Your UI to the Screen on Mobile Browsers

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">
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
micahditto profile image
Micah Dittmar

How would you do this using typescript?


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

Enter fullscreen mode Exit fullscreen mode

This second resizeOps is taken as an identifier.
Is the first one meant to be a function? I'm not used to seeing const used like this