CSS Full Screen - Position absolute vs 100% height
Asked Answered
W

3

8

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?

Whitman answered 24/11, 2014 at 8:30 Comment(2)
personally i would use min-height:100% so that if your content needs to overflow it can. But im splitting hairs here.Mok
Setting html and body to a fixed height of 100% can easily lead to problems when you have regular content that is higher than that.Andee
O
9

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/

Oscillator answered 24/11, 2014 at 9:25 Comment(1)
For all those, who are facing issues like me, when the content of the different pages have different heights and even sometime 100vh. Setting position: fixed made it work for me.Retrospect
D
8

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

Doublespace answered 28/4, 2016 at 23:9 Comment(0)
C
1

One more way to create a full screen div is to apply height: 100%; to body,html and div , then to apply position:relative to the full screen div. Like the following example:

html,
body {
    height: 100%;
}

div {
    height: 100%;
    position: relative;
}

An example: http://jsfiddle.net/s04scj0m/1/

Carbo answered 24/11, 2014 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.