Absolute Horizontal and Vertical Centering via CSS


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



Copy this code and paste it in your HTML
  1. <body>
  2.  
  3. <div id="distance"></div>
  4. <div id="content">
  5. <!-- absolutely centered content -->
  6. </div>
  7.  
  8. </body>
  9.  
  10.  
  11. html, body {
  12. height: 100%; /* required */
  13. }
  14. body {
  15. text-align: center; /* horizontal centering hack for IE */
  16. padding: 0; /* required to "hide" distance div */
  17. margin: 0; /* required to "hide" distance div */
  18. }
  19. div#distance {
  20. margin-bottom: -10em; /* half of content height */
  21. background: red; /* temporary - used to see div */
  22. width: 1px; /* required to "hide" distance div */
  23. height: 50%; /* required */
  24. float: left; /* required */
  25.  
  26. }
  27. div#content {
  28. position: relative; /* positions content on top of distance */
  29. text-align: left; /* horizontal centering hack for IE */
  30. height: 20em; /* required - desired height */
  31. width: 40em; /* required - desired width */
  32. background: blue; /* cosmetic */
  33. margin: 0 auto; /* required */
  34. clear: left; /* required */
  35. }

URL: http://perishablepress.com/press/2007/09/25/absolute-horizontal-and-vertical-centering-via-css/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.