title: Convert vh units to px in JS
body: <p>Unfortunately <code>100vh</code> is not always the same as <code>100%</code> browser height as can be shown in the following example.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-css lang-css prettyprint-override"><code>html,
  body {
      height: 100%;
  }
  
  body {
      overflow: scroll;
  }
  
  .vh {
      background-color: blue;
      float: left;
      height: 50vh;
      width: 100px;
  }
  
  .pc {
      background-color: green;
      float: left;
      height: 50%;
      width: 100px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="vh"&gt;&lt;/div&gt;
  &lt;div class="pc"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>The issue is more pronounced on iPhone 6+ with how the upper location bar and lower navigation bar expand and contract on scroll, but are not included in the calculation for <code>100vh</code>.</p>
  
  <p>The actual value of <code>100%</code> height can be acquired by using <code>window.innerHeight</code> in JS.</p>
  
  <p><strong>Is there a convenient way to calculate the current conversion of <code>100vh</code> to pixels in JS?</strong></p>
  
  <p>I'm trying to avoid needing to generate dummy elements with inline styles just to calculate <code>100vh</code>.</p>
  
  <p>For purposes of this question, assume a hostile environment where <code>max-width</code> or <code>max-height</code> may be producing incorrect values, and there isn't an existing element with <code>100vh</code> anywhere on the page. Basically, assume that anything that can go wrong <em>has</em> with the exception of native browser functions, which are guaranteed to be clean.</p>
  
  <p>The best I've come up with so far is:</p>
  
  <pre><code>function vh() {
      var div,
          h;
      div = document.createElement('div');
      div.style.height = '100vh';
      div.style.maxHeight = 'none';
      div.style.boxSizing = 'content-box';
      document.body.appendChild(div);
      h = div.clientHeight;
      document.body.removeChild(div);
      return h;
  }
  </code></pre>
  
  <p>but it seems far too verbose for calculating the current value for <code>100vh</code>, and I'm not sure if there are other issues with it.</p>