Posted By

mennyj on 06/18/10


Tagged

align vertical rtcrm


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

okmores


Vertically align within browser window


 / 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.

  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.