Yogi Bear
Yogi Bear

Reputation: 963

100vh and 100vw compared to the current size of the browser window

There are lots of pages discussing vh and vw versus percentage. (I'm running on Chrome btw). In my mind, 100vw should mean the exact size of the browser window no matter whether I expand it or shrink it -- and when I draw a border around a div that's 100vw, IT DOES match that width. HOWEVER, 100vh ALWAYS overflows the bottom of the screen. I've played with:

html, body {
  height: 100%;
  width: 100%;
}

and 

html, body {
  height: 100vh;
  width: 100vw;
}

and when I draw a border around a div that's 100vw and 100vh, the box overflows the bottom of the screen.

WHAT (if anything) am I missing here? To me 100vh goes to the bottom of the currently browser window size and not a pixel more.

Thanks in advance

Upvotes: 1

Views: 3992

Answers (1)

Alexis Vandepitte
Alexis Vandepitte

Reputation: 2088

Add *, *::before,*::after { box-sizing: border-box; } at the start of your file, the border will now be part of the width, like the padding.

Check there : https://developer.mozilla.org/fr/docs/Web/CSS/box-sizing

By default, the box-sizing is set to content-box, that mean that when you set:

width: 100px;
padding: 20px;
border: 5px;

The total width will be 100 of content + 20 padding + twice 5 (5 for border-left, and 5 for border-right) = 130px;

If you set the box-sizing to border-box it will include the borders and padding in the width

So the width will always be the width that you set, regardless to the border and padding, and it will automatically calculate the width for the content : 100px - 20px - 2 * 5px = 70px;

Example:

$('#toggleBoxSizing').on('click', function(){
    $('div').toggleClass('contentbox');
});
*, *::before, *::after {
    box-sizing: border-box;
}
html, body {padding: 0; margin: 0; }

div {
  height: 100vh;
  width: 100vw;
  border: 4px solid black;
}

div.contentbox {
  box-sizing: content-box;
}

#toggleBoxSizing {
   margin: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

    <button id="toggleBoxSizing">Toggle "box-sizing: border-box;"</button>
</div>

Upvotes: 4

Related Questions