1

This is my simple code

<!DOCTYPE html>
<html>
    <head>
        <style>
            div{height:100%;width:100%;background:red;position:relative;}
        </style>
    </head>
    <body>
        <div></div>
    </body>
</html>

CSS height 100% is not applying for DIV.

I know some other css code to obtain this. But why this code is not working. how to work on height 100% and width 100% without any script.

Natesan
  • 1,135
  • 2
  • 14
  • 21

2 Answers2

7

For % to work you need to set height for parent element as well.

Set html, body {height: 100%}

From the Docs -

The is calculated with respect to the height of the containing block. If the height of the containing block is not specified explicitly, the value computes to auto. A percentage height on the root element (e.g. ) is relative to the initial containing block (whose dimensions are equal to the dimensions of the viewport).

Check more on this at - MDN Percent Doc

So in your case, you can do like this -

<!DOCTYPE html>
<html>
    <head>
        <style>
            html,body{height:100%;}
        div{height:100%;width:100%;background:red;position:relative;}
        </style>
    </head>
    <body>
        <div></div>
    </body>
</html>
swapnesh
  • 26,318
  • 22
  • 94
  • 126
2

You can accomplish this using position:aboslute;

jsFiddle

div {
    background:red;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
}
body {
    background-color:blue;
}

Alternatively you can set html and body height also to 100%, if going this route be sure to strip the margin from body.

jsFiddle (with margin, notice scrollbars)
jsFiddle (without margin)

html, 
body {
    height:100%;
    margin: 0;
}
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166