Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't HTML and BODY take all available height of document when min-height: 100%? [duplicate]

Tags:

html

css

I have been struggling to understand this scenario

I have set, in CSS

html, body {
    min-height: 100%;
}

So that when there is no content on the page, the html and body take 100% of the height of page. And if there is content in body, these should change their height according to content height.

But when I add some content on the page (enough to display scroll bar), html and body are not taking 100% height of the document. i.e. if my screen height is 700px, in either case $('body').height() would return 700px;

Why is that?

EDIT: In other words, I want my body Tag to be at least 100% of screen but it should grow if content is added.

like image 437
U.P Avatar asked Jun 01 '13 09:06

U.P


2 Answers

I've misread the question at first, but on second thought I'd interpret it as:

The html element ignores min-height: 100%.

Why is that?

The answer to "Why" is in the relevant spec, emphasis mine:

min-height

...

Value: <length> | <percentage> | inherit

...

<percentage>
Specifies a percentage for determining the used value. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').

This is why you need to set a height for the html element for min-height to work on the body element. Alternatively you can position the html element absolutely, like this:

html { border: 10px solid black }
body { border: 10px dashed red }

html { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }    
/* alternatively: html { min-height: 100%; height: 100%; } */    

html { min-height: 100%; }
body { min-height: 100%; }

See the position: absolute demo or the height: 100% demo.

Thanks to @Alohci for correcting me on the interpretation of the spec.

like image 165
Jeroen Avatar answered Sep 20 '22 16:09

Jeroen


In the case you describe, html and body do take up 100% of the screen height. Add a background-color to see this:

body {
    background-color: lightblue;
}

You'll see the entire screen is now coloured. The jquery statement you're getting .height() from is still only returning the height of the content, not being stretched to the height of the screen. When you have a scrollbar, .height() of body will return the height of all the content, not just the visible area. You can get the height of the window with $(window).height(). See this fiddle for a demo.

like image 28
Richard Avatar answered Sep 18 '22 16:09

Richard