Exact Position Within Viewport
The size of the viewport sometimes is the size of the screen. But not always.
A viewport is the size of the browser's window where a web page is displayed.
There is a way to place something, a div for example, in an exact position within a viewport — regardless of viewport size.
The CSS position:fixed;
is used. It places the div within the viewport and keeps it in position no matter how much the web page is scrolled.
But the div must still be told where to be. Using exact pixel measurements is not the way. Example:
position:fixed; top:150px; left:300px;
While the above might work for some viewport sizes, it is unlikely to work with all.
To specify a position valid within any viewport, let's use the vh
and vw
measurements. Example:
position:fixed; top:15vh; left:30vw;
That would work for any viewport size.
The 15vh
value specifies 15% of the viewport height. Thus, top:15vh;
places the div down from the top by the distance that equals 15% of the viewport's height.
Similarly, the 30vw
value specifies 30% of the viewport width. Thus, left:30vw;
places the div in from the left by the distance that equals 30% of the viewport's width.
The reason it would work for any viewport size is because vh
and vw
measurements are percentage of viewport height and percentage of viewport width, respectively.
Use vh
and vw
for good cross-device and cross-browser positioning within the viewport.
Let's finish this article with a technique for centering something within the viewport, regardless of the viewport's dimension.
The width and height of the div to be centered needs to be known. For this example code, let's assume the div's dimensions are 100px high and 150px wide.
To center the div, we use the CSS calc
feature.
To calculate for the vertical centering, we calculate one-half height of the viewport minus one-half height of the div.
Similarly, for horizontal centering, one-half viewport width minus one-half div width.
Here it is:
<div style="width:200px; height:100px; background-color:rgba(0,0,255,.2); position:fixed; top:calc(50vh - 50px); left:calc(50vw - 75px);"></div>
The blue-colored parts in the above code are where the calculations take place.
Using the vh
and vw
CSS measurements lets you position web page content within any viewport size.
(This content first appeared in Possibilities newsletter.)
Will Bontrager