/ Published in: JavaScript
[via rtcrm]
This will vertically align a block-level element inside the user's browser window and will automatically adjust if the window is resized.
This will vertically align a block-level element inside the user's browser window and will automatically adjust if the window is resized.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<body> <div id="verticalContainer"> This text will always be vertically centered inside the browser window </div> </body> function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('verticalContainer'); // Be sure to specify the correct ID var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onresize = function() { setContent(); } // If this is being used with a JS framework (jQuery, prototype,etc...) // remove the window.onload function and put setContent() inside the // framework's proprietary "onload" function to avoid conflicts window.onload = function() { setContent(); }