簡體   English   中英

與相對和絕對定位對齊

[英]Alignment with relative and absolute positioning

我怎么能把藍色盒子放在紅色盒子里? 我看到藍色框的左側正好位於紅色框的中間,但我想將整個藍色框放在中心,而不是左側。 盒子的尺寸不是恆定的。 無論盒子尺寸如何,我都想對齊。 在這里玩的例子。 謝謝 !

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

截圖

如果您能夠將<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; }

我認為最好為封閉的盒子使用更多的自動化,因為如果更改容器盒的大小,則需要更少的更改。

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

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

如果你要定義那樣的尺寸(200px x 300px和300px x 400px),這里是它如何居中:

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

您可以在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;
    }

這應該工作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM