相对定位和绝对定位的对齐方式

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

Screenshot

5个回答

2

如果您能将标签更改为

标签

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

我认为在封闭的盒子中使用更多的自动化是更好的选择,这样如果您更改容器盒子的大小,需要做的更改就会更少。


1

如果您只需要这样做,可以将left:50px添加到#abs中...

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

我的意思是盒子的尺寸未知。我想要无论盒子尺寸如何都能对齐。 - Misha Moroshko

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

你是想让整个盒子居中吗?还是只想左/右对齐居中? - Brant

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

-2

这应该可以运行

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

左/右自动技巧(例如使用margin居中div)在这里不起作用。 - Brant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接