Div centered vertically and horizontally

I need a way to centre a Div on a page both vertically and horizontally but also to reposition on resize or page scroll.

I found an example in JQuery which does what I need, however Id like to keep everything under the same language, so instead of changing all my Javascript t JQuery, Id prefer to find this in Javascript.

$(window).resize(function(){

	$('.className').css({
		position:'absolute',
		left: ($(window).width() - $('.className').outerWidth())/2,
		top: ($(window).height() - $('.className').outerHeight())/2
	});

});

// To initially run the function:
$(window).resize();

Open in new window


http://tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/


Any ideas, or suggestions for a Javascript version?
tonelm54Asked:
Who is Participating?
 
ProculopsisCommented:

//Try this:

window.onload = onWindowResize;
window.onresize = onWindowResize;

function onWindowResize() {
  var element = document.getElementById('rePostitionDiv');
  element.style.position = "absolute";
  element.style.left = ( screen.availWidth - element.clientWidth ) / 2;
  element.style.top = ( screen.availHeight - element.clientHeight ) / 2;
}

0
 
ProculopsisCommented:

CSS should do it for you:

<style>
#centered { position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; width: 100px; height: 100px; border: 1px dashed red; }
</style>

<div id="centered"></div>
0
 
tonelm54Author Commented:
The problem is that wont reposition when the screen is resized.

Ive tried to make my own code, but doesnt seem to work, hopefully its easy to understand.

<html>
    <head">
        <title></title>

        <script language="Javascript">
            document.body.onresize = onWindResize();

            function onWindResize() {
                document.getElementById('rePostitionDiv').offsetLeft = screen.width - document.getElementById('rePostitionDiv').style("width") / 2;
                document.getElementById('rePostitionDiv').offsetTop = screen.height - document.getElementById('rePostitionDiv').style("height") / 2;
            }

            //Call it now
            onWindResize();
        </script>
    </head>
    <body>
        <div id="rePostitionDiv" style="width:200px; height:200px; background-color:Aqua;">
        </div>
    </body>
</html>

Open in new window

0
 
tonelm54Author Commented:
It doesnt re-position when the window is resized :-(
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.