2011-03-28 44 views
24

我有一些HTML頂部一個DIV與兩個div:顯示在另一個

<div> 
    <div id="backdrop"><img alt="" src='/backdrop.png' /></div> 
    <div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div> 
</div> 

我想第二個div #curtain出現在DIV #backdrop頂部。兩個div的大小相同,但我不確定如何將第二個div放在另一個的頂部。

+0

你好,請試試style'float:left;'; – alibenmessaoud 2011-03-28 00:04:49

回答

16

有很多方法可以做到這一點,但這非常簡單,並且避免了干擾內聯內容定位的問題。您可能還需要調整邊距/填充。

#backdrop, #curtain { 
    height: 100px; 
    width: 200px; 
} 

#curtain { 
    position: relative; 
    top: -100px; 
} 
+0

+1因爲你沒有用'絕對'很好的保留位置,謝謝。 – 2014-01-30 15:27:16

+0

但是這種方法不是非常靈敏。如果您放大或調整屏幕大小,這些項目可能不在位置 – Sanity1123 2017-01-23 09:37:25

+1

@ Sanity1123這是因爲此答案在響應式網頁設計起飛之前。 – coreyward 2017-01-23 15:29:34

33

使用CSS position: absolute;隨後top: 0px; left 0px;每個DIV的style屬性。用你想要的任何東西替換像素值。

您可以使用z-index: x;設置垂直「順序」(哪一個是「頂部」)。用數字替換x,數字越大,數字越小。

這是你的新的代碼是什麼樣子:

<div> 
    <div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div> 
    <div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div> 
</div> 
1

這裏是jsFiddle

#backdrop{border:2px solid red; 
width:400px; 
    height:200px; 
    position:absolute; 
} 

#curtain { 
    border:1px solid blue; 
    width:400px; 
    height:200px; 
    position:absolute; 
} 

使用Z-指數移動你想在上面的一個。

3

要正確顯示在另一個上面一個DIV,我們需要按如下方式使用屬性position

  • 外格:position: relative
  • 內部格:position: absolute

我找到了很好的例子here

.dvContainer { 
 
    position: relative; 
 
    display: inline-block; 
 
    width: 300px; 
 
    height: 200px; 
 
    background-color: #ccc; 
 
} 
 

 
.dvInsideTL { 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    width: 150px; 
 
    height: 100px; 
 
    background-color: #ff751a; 
 
    opacity: 0.5; 
 
}
<div class="dvContainer"> 
 
    <table style="width:100%;height:100%;"> 
 
    <tr> 
 
     <td style="width:50%;text-align:center">Top Left</td> 
 
     <td style="width:50%;text-align:center">Top Right</td> 
 
    </tr> 
 
    <tr> 
 
     <td style="width:50%;text-align:center">Bottom Left</td> 
 
     <td style="width:50%;text-align:center">Bottom Right</td> 
 
    </tr> 
 
    </table> 
 
    <div class="dvInsideTL"> 
 
    </div> 
 
</div>

我希望這有助於
字形。