6

我怎么能把蓝色盒子放在红色盒子的中心?我看到蓝色框的左侧正好在红色框的中间,但我想将整个蓝色框居中,而不是左侧。盒子的尺寸不是恒定的。无论盒子尺寸如何,我都想对齐。在这里玩的例子。谢谢 !

HTML:

<div id="rel">
    <span id="abs">Why I'm not centered ?</span>
</div>

CSS:

#rel {
    position: relative;
    top: 10px;
    left: 20px;
    width: 400px;
    height: 300px;
    border: 1px solid red;
    text-align: center;
}

#abs {
    position: absolute;
    bottom: 15px;
    width: 300px;
    height: 200px;
    border: 1px solid blue;
}

截屏

4

5 回答 5

2

如果您能够将<span>标签更改为<div>

<div id="rel">
    <div id="abs">Why I'm not centered ?</div>
</div>

那么这段 CSS 应该可以工作了。

#rel {
position: absolute;
top: 10px;
left: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center; }

#abs {
width: 300px;
height: 200px;
border: 1px solid blue;
margin: auto;
margin-top: 50px; }

我认为最好对封闭的盒子使用更多的自动化,因为如果您更改容器盒的大小,则需要较少的更改。

于 2010-05-20T15:49:23.273 回答
1

如果这就是你想要的,left:50px你可以添加...#abs

#abs {
    position: absolute;
    bottom: 15px;
    width: 300px;
    height: 200px;
    border: 1px solid blue;
    left:50px;
}
于 2010-05-20T15:09:53.033 回答
1

如果您要定义这样的尺寸(200 像素 x 300 像素和 300 像素 x 400 像素),它可以这样居中:

#rel {
    position: relative;
    top: 10px;
    left: 20px;
    width: 400px;
    height: 300px;
    border: 1px solid red;
    text-align: center;
}

#abs {
    position: absolute;
    width: 300px;
    height: 200px;
    border: 1px solid blue;
    margin: 49px 0 0 49px;
}
于 2010-05-20T15:13:57.080 回答
0

您可以在http://jsfiddle.net/NN68Z/96/上查看我的解决方案

我对css做了以下

    #rel {
        position: relative;
        top: 10px;
        left: 20px;
        right: 20px;
        width: 400px;
        height: 300px;
        border: 1px solid red;
        text-align: center;

        display: table-cell;
        vertical-align: middle;
    }

    #abs {
        display: block;
        bottom: 15px;
        width: 300px;
        height: 200px;
        border: 1px solid blue;
        margin: 0 auto;
    }
于 2013-06-21T10:09:19.347 回答
-2

这应该工作

#abs {
    position: absolute;
    left: auto;
    right: auto;
    bottom: 15px;
    width: 300px;
    height: 200px;
    border: 1px solid blue;
}
于 2010-05-20T15:18:51.410 回答