簡體   English   中英

當兩個div都使用自動邊距居中時,如何將一個div放在另一個頂部?

[英]how to place one div on top of another, when both are centered using auto margin?

我有2個div,一個square和一個bar 兩者都使用auto邊距居中。 但是我想在正方形上放置欄。 我怎樣才能做到這一點?

html

<div class="square">square</div>
<div class="bar">square</div>

的CSS

.square,.bar{
    margin-left:auto;
    margin-right:auto
}
.square{
    background-color:blue;
    width: 100px;
    height: 100px;
}
.bar{
    background-color:green;
    width: 400px;
    height: 40px;
}

是小提琴。

您可以這樣做: http : //jsfiddle.net/mz6rk/

我將position:relative放置在-square_height/2 - bar_height/2

這確實假設您知道正方形和條形的高度,但我不知道是否總是這樣。

更新:實際上,只有小節需要具有position:relative (我把它放在小提琴中)。

http://jsfiddle.net/atomicrevolution/P9yWK/5/

你是這個意思嗎?

.square,.bar{
    margin-left:auto;
    margin-right:auto;
}
.square{
    background-color:blue;
    width: 100px;
    height: 100px;
    position: relative;
}
.bar{
    background-color:green;
    width: 400px;
    height: 40px;
    position: relative;
    margin-top: -70px;
}

暫無
暫無

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

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