Perhaps horizontal centering of a div without knowing the width of the div?

I am currently creating a script popup using css / jquery, and I cannot get the div to focus on the screen in all cases. Is it possible to center it without knowing the width of the div?

Instead of posting all the code here, I set a live example at http://goo.gl/N45cp

Any help is much appreciated!

Best regards John

+3
source share
2 answers
<div id="wrapper">
    <div id="child"></div>
</div>

If the position is #childnot absolute, you can set the left and right margins to auto:

#child {
   margin: 0 auto;
}

Or, if the position is absolute, you can try the following:

$("#child").css("left", function(){
    return ($("#wrapper").width() - $(this).width()) / 2;
});
+7
source

You can achieve this with pure CSS if you have a containing div:

HTML

​<div id="outer">
    <div id="inner">some content here</div>
</div>

CSS

​body, html, div#outer { height:100%; }
div#outer { text-align:center; }
div#inner { display:inline-block; }

http://jsfiddle.net/NjZbW/

+4

All Articles