css – What differences are there really between vh/vw and %?

Question:

Applying CSS to a site, I had a doubt in CSS when I wanted to define a variable size of an HTML container.

What is the appropriate use to use vh/vw or percentage % , in which cases should one be used and in which others the other?

Answer:

vh (Viewport Height)

Measurement based on screen height. For example if we give an element a height of height: 100vh; , this element will be the same height as the screen.

vw (Viewport Width)

Measurement based on the width of the screen. For example if we give a width to an element of width: 100vw; , this element will have the same width as the width of the screen.

% (Percentage)

Percentage based measurement. The measurement in percentage will be defined in relation to its parent element, unless it is accompanied by a fixed position ( position:fixed; ) or absolute ( position:absolute; ), which then in this case its behavior will now also respect the size from the screen.

Consider the following example:

var docH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var viewportH = document.querySelector('.vh-height').offsetHeight;
var percentH = document.querySelector('.percent-height').offsetHeight;

var dhOut = document.getElementById('doc-height');
var vhOut = document.getElementById('vh-height');
var pctOut = document.getElementById('percent-height');

dhOut.innerHTML = docH;
vhOut.innerHTML = viewportH;
pctOut.innerHTML = percentH;
body {
    background-color: #cbcbcb;
}
#parent{
    height:130px;
    width:400px;
    overflow: auto;
    background-color: #eee;
}
.child{
    width: 50%; /* 50% de ancho del elemento parent */
    color: #fff;
}
.vh-height{
    float:left;
    height:100vh; /* 100% de altura de viewPort */
    background-color:royalblue;
}
.percent-height{
    float:right;
    height:100%; /* 100% de altura pero relativamente a su elemento padre */
    background-color:brown;
}
uno
<div id="parent">
    <div class="child vh-height">dos</div>
    <div class="child percent-height">tres</div>
</div>

(uno)  Altura del Documento/Viewport: <span id="doc-height"></span><br/>
(dos)  Altura del Viewport: <span id="vh-height"></span><br/>
(tres) Altura en Porcentaje (igual > altura del parent): <span id="percent-height"></span><br/>

You can also see this example on jsFiddle

Scroll to Top