Stretching a CSS Div to 100% Page Height Without JavaScript
Enhancing the user experience of a website involves ensuring that page elements behave as expected. One common requirement is to have navigation bars or other elements stretch vertically to fill the entire page height, regardless of viewport size or scrolling. While JavaScript can achieve this, a purely HTML/CSS solution offers advantages such as flexibility and ease of implementation.
Solution:
After experimenting with various approaches, the following CSS and HTML structure emerged as the optimal solution for stretching a DIV to 100% page height:
<code class="css">/* Ensure the HTML element stretches to the full page height */ html { min-height: 100%; position: relative; } /* Force the body element to match the HTML element's height */ body { height: 100%; } /* Position the DIV container absolutely and stretch it to all sides */ #cloud-container { position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow: hidden; z-index: -1; /* Only applies to background elements */ }</code>
<code class="html"><!doctype html> <html> <body> <div id="cloud-container"></div> </body> </html></code>
Explanation:
The html element is made the reference for measurements and positioned relatively, which prevents its children elements from being removed from its layout. The body element's height is set to 100%, ensuring it matches the height of the html element.
The #cloud-container DIV's absolute positioning, combined with its top/bottom/left/right set to 0, ensures it occupies the entire available space. The overflow: hidden property prevents the content from overflowing the container.
Rationale:
By positioning the #cloud-container DIV as a child of the html element and using the position: relative property on the html element, it is guaranteed to occupy the full height of the page, even when the content is longer than the viewport. This approach is robust and widely compatible across different browsers.
The above is the detailed content of How to Stretch a CSS Div to 100% Page Height Without JavaScript?. For more information, please follow other related articles on the PHP Chinese website!