We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

rtcrm on 10/27/08


Tagged

align vertical rtcrm


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

SpinZ
jamesming


Vertically align within browser window


Published in: JavaScript 


This will vertically align a block-level element inside the user's browser window and will automatically adjust if the window is resized.

RTCRM

  1. <body>
  2. <div id="verticalContainer">
  3. This text will always be vertically centered inside the browser window
  4. </div>
  5. </body>
  6.  
  7.  
  8. function getWindowHeight() {
  9. var windowHeight = 0;
  10. if (typeof(window.innerHeight) == 'number') {
  11. windowHeight = window.innerHeight;
  12. }
  13. else {
  14. if (document.documentElement && document.documentElement.clientHeight) {
  15. windowHeight = document.documentElement.clientHeight;
  16. }
  17. else {
  18. if (document.body && document.body.clientHeight) {
  19. windowHeight = document.body.clientHeight;
  20. }
  21. }
  22. }
  23. return windowHeight;
  24. }
  25.  
  26. function setContent() {
  27. if (document.getElementById) {
  28. var windowHeight = getWindowHeight();
  29. if (windowHeight > 0) {
  30. var contentElement = document.getElementById('verticalContainer'); // Be sure to specify the correct ID
  31. var contentHeight = contentElement.offsetHeight;
  32. if (windowHeight - contentHeight > 0) {
  33. contentElement.style.position = 'relative';
  34. contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
  35. }
  36. else {
  37. contentElement.style.position = 'static';
  38. }
  39. }
  40. }
  41. }
  42.  
  43. window.onresize = function() {
  44. setContent();
  45. }
  46.  
  47. // If this is being used with a JS framework (jQuery, prototype,etc...)
  48. // remove the window.onload function and put setContent() inside the
  49. // framework's proprietary "onload" function to avoid conflicts
  50. window.onload = function() {
  51. setContent();
  52. }

Report this snippet 

You need to login to post a comment.