2013-12-10 53 views
4

虽然这看起来很像很多已存在的帖子,但我找不到解决方案。在没有固定宽度或高度的div中居中放置内容

我有以下HTML:

<div class="outer-zone"> 
    <div> 
     Outer zone. 
    </div> 
    <div class="inner-zone"> 
     Inner zone here... 
    </div> 
</div> 

和相应的类,如下所示:

.outer-zone { 
    background-color : navy; 
    color : whitesmoke; 
    width : 90%; 
    height: 50%; 
    text-align: center; 
    margin-left: auto; 
    margin-right: auto; 
} 

.inner-zone { 
    background-color : deepskyblue; 
    color : navy; 
    width : 75%; 
    height : 40%; 
    margin-left: auto; 
    margin-right: auto; 
} 

我想实现是有outer-zone格,居中(垂直和水平)在页面中,和inner-div,集中在外部div。

到目前为止,我发现的所有内容都是如何在固定高度的div内对齐内容。我想保留这些div宽度和高度。

结果到目前为止,看起来是这样的:

(拖动图片有点要注意底部的空格)

enter image description here

+1

据我所知,你会需要一个固定的像素,而不是百分比(我只是在周五做这个工作,找不到工作pecentage周围很简单) –

+0

我觉得@ RUJordan是正确的。 margin-left:auto需要固定的宽度。 – Liam

+0

它已经水平居中,我的问题实际上是垂直居中。 – VasileF

回答

1

这将这样的伎俩:

您需要将您的内容与display:table分隔,并将高度/宽度缩小为50%和90%。 然后将您的.outer-zone设置为display:table-cell; vartical-align:middle

FIDDLE

HTML:

<div class="page"> 
    <div class="wrap"> 
     <div class="outer-zone"> 
      <div> 
       Outer zone. 
      </div> 
      <div class="inner-zone"> 
       Inner zone here... 
      </div> 
     </div> 
    </div> 
</div> 

CSS:

html,body{ 
    height:100%; 
    width:100%; 
    display:table; 
} 
.page{ 
    display:table-cell; 
    vertical-align:middle; 
} 
.wrap{ 
    width:90%; 
    height:50%; 
    display:table; 
    margin:0 auto; 
} 
.outer-zone { 
    display:table-cell; 
    vertical-align:middle; 
    background-color : navy; 
    color : whitesmoke; 
    text-align: center; 
    margin-left: auto; 
    margin-right: auto; 
} 

.inner-zone { 
    background-color : deepskyblue; 
    color : navy; 
    width : 75%; 
    height : 40%; 
    margin:0 auto; 
} 
+0

+1,你打我吧!与一些jQuery的 – Abhitalks

+0

,你可以使页面居中。 http://jsfiddle.net/tVJ3U/15/ –

+0

@chadocat:外部div不再尊重宽度90%和高度50%。 – VasileF

0

试试这个小提琴:

http://jsfiddle.net/PU3Rw/

CSS:

html,body{display:table;width:100%;height:100%;} 

.main{ 
    display: table-cell; 
    vertical-align: middle; 
    height:100%; 
    width:100%; 
    position:relative; 
} 
相关问题