简体   繁体   English

如何在绝对位置的div内居中放置div?

[英]How can I center a div inside an absolutely positioned div?

I am using a fluid layout design and I want the div with class center to be centered horizontally inside of the div with class outer . 我正在使用流畅的布局设计,我希望班级center的div在班级class outer的div中水平居中。 I tried this, but it doesn't work. 我试过了,但是没有用。 What am I doing wrong? 我究竟做错了什么?

HTML: HTML:

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

CSS: CSS:

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

.inner {
    width:100%;
}

.center {
    margin:0 auto;
}

You've gotta treat the inner as if it's a regular div in a page, so something like: 您必须将内部视作页面中的常规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;
}

This would do the trick and you can adjust accordingly . 这可以解决问题,您可以进行相应调整。

use a percentage for margin-left, eg: 使用百分比表示左边距,例如:

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

the reason I used 5% is because since the width of center is 90% of it's container, we have 10% of space remaining, so to center it you'll have to bring it over to the left by half of the available space; 我使用5%的原因是因为中心的宽度是其容器的90%,所以我们还有10%的剩余空间,因此要居中,您必须将其向左移至可用空间的一半; which in this case is 5% 在这种情况下是5%

Inline-block is probably the best option for the centered div, then use our outer div with text-align:center to center the inner container. 内联块可能是居中div的最佳选择,然后将外部div与text-align:center一起使用来使内部容器居中。 You don't really need an inner and a center div the way you have it, but I kept it in for examples sake. 实际上,您实际上并不需要内部和中心div,但是出于示例目的,我保留了它。 Below is a fiddle link: 下面是一个小提琴链接:

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

Borders and padding added for example. 例如,添加了边框和填充。

<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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM