2

I have DIV element that I want to appear the full size of the browser but will have some padding and rounded corners. That part is easy, but I want it to resize when the keyboard is shown to be the size of the new viewport. I am able to do this just fine with Javascript using window.visualViewport.height. The problem is that some browsers are not giving exactly the right size, so the DIV isn't showing up correctly. Is there any way to do this with pure CSS or in another way that will always work for all browsers?

Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64
Ray
  • 187
  • 1
  • 7
  • 1
    You should be able to do this with [viewport](https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts), like `height: 100vw` – Alicia Sykes Apr 26 '22 at 22:05

1 Answers1

0

One solution would be to use viewport, which is a dynamic value representing the current visible area. vh is heaigh, and vw is width, and both are equal to 1% of the screens height/ width.

With this method, when the soft keyboard is opened, this area shrinks, as does your container.

First, add this meta tag, so that the viewport represents the actual device size, and not zoomed in size:

<meta name="viewport" content="width=device-width">

Next, just set height to use the screen height, with:

height: 100vh;

And if you want to deduct a fixed amount of space, then you could use calc, e.g:

height: calc(100vh - 0.5rem)

Demo

Based on your screenshots, here's an example:

.container {
  background: #e3e3e3;
  border-radius: 0.5rem;
  height: calc(100vh - 1rem);
  width: calc(100% - 1rem);
  margin: 0 auto;
}
<head>
  <meta name="viewport" content="width=device-width">
</head>

<body>
  <div class="container"></div>
</body>
Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64
  • 1
    @Ray - Did that help you? If so, consider accepting, if not explain what still isn't working and I can update the answer. – Alicia Sykes Apr 29 '22 at 13:50