tags:

views:

810

answers:

3

I am trying to set a div to a certain percentage height in CSS, but it just remains the same size as the content. When I remove the doctype element at the top of the page, however, it works. I want the page to validate, so what should I do?

The code is as follows:

#page {

padding: 10px;

background-color: white;

height: 90% !important;

}
+1  A: 

Your question is unanswerable.

Why doesn't it work?
What happens?
What "element at the top of the page"? (The DOCTYPE?)

Please provide more details.

SLaks
+2  A: 

You need to set the height on the <html> and <body> elements as well; otherwise, they will only be large enough to fit the content. For example:

<!DOCTYPE html>
<title>Example of 100% width and height</title>
<style>
html, body { height: 100%; width: 100%; margin: 0; }
div { height: 100%; width: 100%; background: red; }
</style>
<div></div>
Brian Campbell
+3  A: 

I am trying to set a div to a certain percentage height in CSS

Percentage of what?

To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.

So the parent of the div must have an explicit height property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.

If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html> and <body>, have to have height: 100%, so there is a chain of explicit percentage heights down to the div.

(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)

bobince