Emaborsa
Emaborsa

Reputation: 2860

Center a div using Javascript

I'm trying to center a div (screen center). This div is not a direct child of the body so I can't use css. Currently I use the following jQuery code in order to center it on my page:

    var dialog = $('#MyDialog');
    dialog.css('left', ($('body').width()/2) - (dialog.width()/2));
    dialog.css('top', ($('body').height()/2) - (dialog.height()/2);

The goal is to remove jQuery, I've already written this:

var showDialog = function(){

    var body = document.body;
    var html = document.documentElement;

    var bodyHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
    var bodyWidth = Math.max( body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth );

    var dialogWidth = 800;
    var dialogHeight = 560;

    var dialog = document.getElementById('MyDialog');
    dialog.style.left = (bodyWidth/2) - (dialogWidth/2) + 'px';
    dialog.style.top = (bodyHeight/2) - (dialogHeight/2) + 'px';

    dialog.style.display = "block";
}

The point is that dialogWidth and dialogHeight are dynamic. How can get them?

Upvotes: 1

Views: 20015

Answers (2)

Aswita Hidayat
Aswita Hidayat

Reputation: 159

You need to use DOM style

try this :

function myFunction() {
    document.getElementById("MyDialog").style.position = "relative";
    document.getElementById("MyDialog").style.left = "50%";
   document.getElementById("MyDialog").style.right = "50%";
}

Upvotes: 2

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15851

Centering through CSS is a better pratice, if you can center it with JS, you can with css for sure.

try with:

#MyDialog {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: xxx; // Any width will be fine
    height: xxx: // Any height will be fine
}

Upvotes: 9

Related Questions