如何将div放在绝对定位的div中?

时间:2012-12-10 01:19:56

标签: html css

我正在使用流畅的布局设计,我希望类center的div在div中使用类outer水平居中。我试过这个,但它不起作用。我做错了什么?

HTML:

<div class="outer">
    <div class="inner"> // this div has height=0. Why?
        <div class="center">
            // stuff
        </div>
    </div>
</div>

CSS:

.outer {
    position: absolute;
    left: 0;
    right: 0;
    top: 50px;
    height: auto;
}

.inner {
    width:100%;
}

.center {
    margin:0 auto;
}

3 个答案:

答案 0 :(得分:0)

你必须把内心当作一个页面中的常规div对待,如下所示:

#inner {
    position:fixed;
    top: 50%;
    left: 50%;
    width:234px;
    height:90px;
    margin-top:-45px; /*set to a negative number 1/2 of your height*/
    margin-left:-117px; /*set to a negative number 1/2 of your width*/
    border: 0.5px solid #ccc;
}

这可以解决问题,你可以相应调整。

答案 1 :(得分:0)

使用margin-left的百分比,例如:

.center
{
width:90%;
margin-left:5%;
}

我使用5%的原因是因为由于中心的宽度是它的容器的90%,我们剩余10%的空间,所以为了使它居中,你必须把它带到剩下一半的可用空间;在这种情况下,这是5%

答案 2 :(得分:0)

内联块可能是居中div的最佳选择,然后使用带有text-align:center的外部div来居中内部容器。你并不像你拥有它那样需要一个内部和一个中心div,但我保留了它的例子。下面是一个小提琴链接:

http://jsfiddle.net/UYw8S/2/

例如,添加了边框和填充。

<div class="outer">
    <div class="inner">
        <div class="center">
           Inner stuff
       </div>
   </div>
</div>

.outer {
position: absolute;
left: 0;
right: 0;
top: 50px;
height: auto;
background:#ccc;
border:1px solid #333;
}

.inner {
display:block;
margin:10px;
border:1px solid #333;
text-align:center;
}

.center {
margin:10px 0;
text-align:left;
height:40px;
width:80%;
display:inline-block;
background:#fff;
padding:10px;
}
相关问题