Vertical Align JQuery Plugin


/ Published in: jQuery
Save to your folder(s)

Learn how to place a DIV in the exact middle of the screen using this JQuery horizontal & vertical align plugin.


Copy this code and paste it in your HTML
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <title>Demo</title>
  5.  
  6. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  7.  
  8. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
  9.  
  10. <script type="text/javascript">
  11. (function ($) {
  12. $.fn.vAlign = function() {
  13. return this.each(function(i){
  14. var h = $(this).height();
  15. var oh = $(this).outerHeight();
  16. var mt = (h + (oh - h)) / 2;
  17. $(this).css("margin-top", "-" + mt + "px");
  18. $(this).css("top", "50%");
  19. $(this).css("position", "absolute");
  20. });
  21. };
  22. })(jQuery);
  23.  
  24. (function ($) {
  25. $.fn.hAlign = function() {
  26. return this.each(function(i){
  27. var w = $(this).width();
  28. var ow = $(this).outerWidth();
  29. var ml = (w + (ow - w)) / 2;
  30. $(this).css("margin-left", "-" + ml + "px");
  31. $(this).css("left", "50%");
  32. $(this).css("position", "absolute");
  33. });
  34. };
  35. })(jQuery);
  36.  
  37. $(document).ready(function() {
  38. $("#content").vAlign();
  39. $("#content").hAlign();
  40. });
  41. </script>
  42.  
  43. <style type="text/css">
  44. html { background: #fafafa; }
  45.  
  46. #content
  47. {
  48. background: #fff;
  49. border: 10px solid #eee;
  50. padding: 20px;
  51. color: #666;
  52. font-family: Arial, Helvetica, sans-serif;
  53. font-size: 12px;
  54. line-height: 25px;
  55. text-align: justify;
  56. }
  57.  
  58. #content { width: 400px; }
  59. </style>
  60.  
  61. </head>
  62.  
  63. <body>
  64.  
  65. <div id="content">
  66. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas eu dui eget nulla condimentum gravida. Vivamus erat leo, ultricies quis, gravida a, fringilla eu, urna. Pellentesque a mauris ac nisl semper egestas. Pellentesque ut elit in pede mattis gravida. Donec ac lectus a nisi suscipit placerat. Maecenas quis ipsum. Pellentesque mattis tellus. Suspendisse sollicitudin accumsan tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed metus. Quisque et leo at erat rutrum lobortis. In tempus lectus eget ligula convallis tristique.
  67. </div>
  68.  
  69. </body>
  70. </html>

URL: http://www.nealgrosskopf.com/tech/thread.asp?pid=37

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.