Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div Height in Percentage [duplicate]

Tags:

Possible Duplicate:
Percentage Height HTML 5/CSS

This needs to be a simple one but I why the height specified in percentage for a div is not apply to it.

For example:

<div class="container">   adsf </div> 

CSS:

.container {   width:80%;   height:50%;   background-color:#eee; } 

When I change height from % to px it works perfectly. % is as valid as px but why only px works and % not. here is the jsfiddle

Edit Though I missed the semicolon after 50% in original question which totally spoiled it. In fact what I intended to ask was why does the 50% does not make it consume the 50% of its container. It only takes its height from its content rather than 50% of its container.

like image 668
ZedBee Avatar asked Jan 27 '13 07:01

ZedBee


People also ask

Can we give height in percentage in CSS?

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 value computes to auto .

How do you give a Div 100 percent height?

container div has two parent elements: the <body> and the <html> element. And we all know that the default value of the height property is auto , so if we also set the height of <body> and <html> elements to 100%, the resulting height of the container div becomes equal the 100% height of the browser window.

Why is height percent not working CSS?

You can't base a percentage height on a parent that has no height set otherwise the height should default to auto (content doesn't count as height either). Also you can't base a child's percentage height on a parent that has min or max height set either as it must be a real height.


2 Answers

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{     height: 100%; } div{     height: 50%; } 

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

like image 178
Derek 朕會功夫 Avatar answered Oct 13 '22 10:10

Derek 朕會功夫


You need to give the body and the html a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.

Updated fiddle: http://jsfiddle.net/j8bsS/5/

like image 45
Mr Lister Avatar answered Oct 13 '22 11:10

Mr Lister