How to display an element to the center of the browser
Posted: | Categories: CSS, JavaScript, Programming
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.
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:
Read more...