Alessandro Lacava’s Blog

Google
 

February 16, 2007

How to display an element to the center of the browser

Filed under: Computer, JavaScript, CSS — alessandrolacava @ 12:55 pm

Sometimes you might need to display an element, for example a div, to the center of the browser. Here is an example of how you can do it using JavaScript and CSS.

JavaScript:
  1. function init()
  2. {
  3. // Reference to the element
  4. var loading = document.getElementById("loading");
  5. // The div's width, set within the CSS class
  6. var loadingWidth = loading.offsetWidth;
  7. // The div's width, set within the CSS class
  8. var loadingHeight = loading.offsetHeight;
  9. // The browser's body's width
  10. var documentWidth = document.body.clientWidth;
  11. // The browser's body's height
  12. var documentHeight = document.body.clientHeight;
  13. // Position the element absolutely
  14. loading.style.position = "absolute";
  15. // Center horizontally
  16. loading.style.left = (documentWidth - loadingWidth) / 2;
  17. // Center vertically
  18. loading.style.top = (documentHeight - loadingHeight) / 2;
  19. }

This code supposes you have a div element within your page with id="loading", for example:

HTML:
  1. <div id="loading" class="loading">Loading...</div>
  2. <!-- Other HTML code -->

The CSS class could be the following

CSS:
  1. .loading
  2. {
  3. border: 1px solid #90A6B8;
  4. background-color: #FFFF80;
  5. height: 100px;
  6. width: 300px;
  7. z-index: 1000;
  8. text-align: center;
  9. padding: 20px;
  10. color: #000000;
  11. font-size: 18px;
  12. font-weight: bold;
  13. }

The result should be that the browser displays the div--shown in the following figure--centered within the browser.

Centered Div Example

Centered Div Example

Of course you need to take care of the div hiding and showing according to your needs. For example, when an Ajax call starts/ends you might want to show/hide it , maybe with a "loading gif" within it.