In order to stretch
DIV
element vertically to fit the entire screen (i.e. browser's viewable area), it's not enough just to set its CSS property
height:100%
, it also requires to set CSS properties of
<html>
and
<body>
elements as shown in Listing 1 below:
Listing 1: Vertical stretch using CSS position:relative
<!DOCTYPE html>
<html>
<head>
<title>VERTICAL STRETCH | DEMO</title>
<style type ="text/css">
html {height:100%;}
body {margin:0; padding:0; height:100%;}
div#container {background-color:green; height:100%; width:60%; margin: 0 auto 0 auto;}
</style>
</head>
<body>
<div id="container">
DEMONSTRATION OF DIV HEIGHT:100%
THIS GREEN RECTANGLE SHOULD STRETCH VERTICALLY 100%
</div>
</body>
</html>
Listing 1 snippet implies the default setting of:
position:relative
. Another alternative is to use
position:absolute
and set CSS properties
top
and
bottom
to 0 as shown in the following Listing 2:
Listing 2: Vertical stretch using CSS position:absolute
<!DOCTYPE html>
<html>
<head>
<title>VERTICAL STRETCH | DEMO</title>
<style type ="text/css">
div#container {background-color:green; position:absolute; top:0; bottom:0; width:60%; margin-left:20%; }
</style>
</head>
<body>
<div id="container">
DEMONSTRATION OF DIV HEIGHT:100%
THIS GREEN RECTANGLE SHOULD STRETCH VERTICALLY 100%
</div>
</body>
</html>
Similar results could be achieved by setting CSS
position:fixed
in regards to
DIV
element.
In both cases, make sure that the property
overflow-y
is set correspondingly to the layout specs (either
auto
, or
hidden
,
visible
,
scroll
, etc.) to ensure proper content rendering (refer to the demo sample at:
CSS overflow samples[
^]).