最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Horizontal centering of a div without knowing the div width, possible? - Stack Overflow

programmeradmin5浏览0评论

I'm currently building a popup box script using css/jquery and i can't seem to get the div centered on the screen on all cases. It it possible to center it without knowing the div width?

Instead of posting all the code here i put up a live example at

Any kind of help is much appreciated!

Best Regards John

I'm currently building a popup box script using css/jquery and i can't seem to get the div centered on the screen on all cases. It it possible to center it without knowing the div width?

Instead of posting all the code here i put up a live example at http://goo.gl/N45cp

Any kind of help is much appreciated!

Best Regards John

Share Improve this question asked May 6, 2012 at 13:48 JohnJohn 3872 gold badges5 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7
<div id="wrapper">
    <div id="child"></div>
</div>

If the position of the #child is not absolute, you can set 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;
});

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

​​​​​​​​​​​​​​

发布评论

评论列表(0)

  1. 暂无评论