When creating a full screen div
in html & css one has two main options:
Using: html, body, #myDiv {height: 100%, width: 100%}
Or: #myDiv{position: absolute; top:0px; bottom:0px; width: 100%}
Is there any advantage of one over the other or can they just be used interchangeably?
Centering div (vertical/horizontally) This height is equal to the viewport height. Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)
height:100vh When you set the height to 100vh, the box element will stretch its height to the full height of the viewport regardless of its parent height.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Whereas the position and dimensions of an element with position:absolute are relative to its containing block, the position and dimensions of an element with position:fixed are always relative to the initial containing block. This is normally the viewport: the browser window or the paper's page box.
Both produce the same effect i.e. have a full screen div. Now the only diff. is between the positioning attribute
Now when you have your css as
html, body, #myDiv {height: 100%, width: 100%}
then the default position attribute is static which means that it will normally flow into the webpage
But when you apply
#myDiv{position: absolute; top:0px; bottom:0px; width: 100%}
It is slightly different than the previous one. With position as absolute it means that this div is relative to the immediate parent element or if there is no parent element then it is relative to the page itself. You can see the effect if you have another div as parent element and u insert some text or an image into #myDiv Also an element with absolute position is removed from the flow of elements on the page which means it will not affect other elements and other elements will not affect it
You can check the jsfiddle link and see for yourself how the position of the text varies in both styles http://jsfiddle.net/sidarth1989/32szd39g/
Viewport relative units are now pretty well supported... so you could do this:
#myDiv {
height: 100vh;
width: 100vw;
}
See here: https://www.w3.org/TR/css3-values/#viewport-relative-lengths
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With