本文共 2400 字,大约阅读时间需要 8 分钟。
本文翻译自:
I want to center a div which is added inside another div. 我想将添加到另一个div内的div居中。
This is the CSS I am currently using. 这是我当前正在使用的CSS。
#outerDiv{ width: 500px; height: 500px; position:relative; } #innerDiv{ width: 284px; height: 290px; position:absolute; top: 50%; left:50%; margin-top: -147px; margin-left: -144px; }
As you can see,the approach I use now depends on values for width and height of innerDiv
.If the width/height changes, I will have to modify the margin-top
and margin-left
values.Is there any generic solution that I can use to center the innerDiv
always irrespective of its size? 如您所见,我现在使用的方法取决于innerDiv
width和height的innerDiv
。如果width / height发生变化,我将不得不修改margin-top
和margin-left
值。始终使用innerDiv
而不考虑其大小?
I figured out that using margin:auto
can horizontally allign the innerDiv to the middle.But what about vertical allign middle? 我发现使用margin:auto
可以水平将innerDiv对齐到中间,但是垂直对齐中间呢?
参考:
I know that question was created year ago... Anyway thanks CSS3 you can easily vertically aligns div in div (example there ) 我知道这个问题是在一年前创建的...无论如何,感谢CSS3,您可以轻松地在div中垂直对齐div(例如 )
div{display:-moz-box;-moz-box-align:center;}Go to Hell!
Another way of achieving this horizontal and vertical centering is: 实现这种水平和垂直居中的另一种方法是:
.Absolute-Center { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0;}
( ) ( )
Instead of tying myself in a knot with hard-to-write and hard-to-maintain CSS (that also needs careful cross-browser validation!) I find it far better to give up on CSS and use instead wonderfully simple HTML 1.0: 与其将自己束缚在难以编写和难以维护的CSS上(这还需要仔细的跨浏览器验证!),不如将它束之高阁,我发现放弃CSS并使用非常简单的HTML 1.0更好:
This accomplishes everything the original poster wanted, and is robust and maintainable. 这样可以完成原始海报所需的一切,并且功能强大且可维护。
I have been using the following solution since over a year, it works with IE 7 and 8 as well. 自一年多以来,我一直在使用以下解决方案,它也可以与IE 7和8一起使用。
Line 1
Line 2
You can do this with a simple javascript (jQuery) block. 您可以使用一个简单的javascript(jQuery)块来执行此操作。
CSS : CSS :
#outerDiv{ height:100%;}
Javascript : Javascript :
转载地址:http://zscnb.baihongyu.com/