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.


		left: ($(window).width() - $('.className').outerWidth())/2,
		top: ($(window).height() - $('.className').outerHeight())/2


// To initially run the function:

Open in new window


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

//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;


CSS should do it for you:

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

<div id="centered"></div>
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.


        <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
        <div id="rePostitionDiv" style="width:200px; height:200px; background-color:Aqua;">

Open in new window

tonelm54Author Commented:
It doesnt re-position when the window is resized :-(
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.