Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

How to Display an Element to the Center of the Browser

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.

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

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

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

The CSS class could be the following

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

The result should be that the browser displays the div centered within the browser.

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.

Comments