Skip to content Skip to sidebar Skip to footer

Position Div To Center Of Visible Area

I'm in the midst of making a lightbox style pop-up for a mailing list sign up, but I want the pop-up to position to the center of the visible page, not just the center of the whole

Solution 1:

You were close! It can be done with CSS alone:

Use position: fixed instead of position: absolute.

Fixed refers to the viewport, while absolute refers to the document. Read all about it!

Solution 2:

var w = $(window).width();
var h = $(window).height();
var d = document.getElementById('my-div');
var divW = $(d).width();
var divH = $(d).height();

d.style.position="absolute";
d.style.top = (h/2)-(divH/2)+"px";
d.style.left = (w/2)-(divW/2)+"px";

Solution 3:

I know this will not solve the question but it is good reference and a starting point: How to position a div in the center of browser window

Position Div Exactly at the center of the screen

<!DOCTYPE html><html ><head><styletype="text/css">.exactCenter { 
           width:200px; 
           height:200px; 
           position: fixed; 
           background-color: #00FF00; 
           top: 50%; 
           left: 50%; 
           margin-top: -100px; 
           margin-left: -100px; 
        } 
      </style></head><body><divclass="exactCenter"></div></body></html>

JSFiddle here and here

Solution 4:

with jQuery:

var left = ($(window).width() - $(.my-div).width()) / 2;
var top = ($(window).height() - $(.my-div).height()) / 2;
$('.my-div').position({top: top + 'px', left: left + 'px});

Solution 5:

Although the accepted answer is best, if you can't set the divs position to fixed, then you can use this pure JavaScript solution.

var myElement = document.getElementById('my-div'),
    pageWidth = window.innerWidth,
    pageHeight = window.innerHeight,
    myElementWidth = myElement.offsetWidth,
    myElementHeight = myElement.offsetHeight;

myElement.style.top = (pageHeight / 2) - (myElementHeight / 2) + "px";
myElement.style.left = (pageWidth / 2) - (myElementWidth / 2) + "px";

JSFiddle

Or a more condensed version:

var w = window,
    elem = document.getElementById('my-div');

elem.style.top = (w.innerHeight/2) - (elem.offsetHeight/2) + 'px';
elem.style.left = (w.innerWidth/2) - (elem.offsetWidth/2) + 'px';

This answer is a vanilla JavaScript version from Lahiru Ashan's answer.

Post a Comment for "Position Div To Center Of Visible Area"