2016-12-16 56 views
0

我有以下HTML(Plunker Example):地點DIV比其它DIV和圖像

<div class="first"> 
    <img src="http://placehold.it/350x150"> 
</div> 

<div class="second"> 
    Lorem Ipsum ... 
</div>   

我需要放置第二DIV在第一DIV的一部分,因此我使用:

body { 
    text-align: center; 
} 

.first { 
    background-color: orange; 
    z-index: 100; 
} 

.first img { 
    display: block; 
    margin: 0 auto; 
} 

.second { 
    background-color: red; 
    margin: -80px 0 auto; 
    z-index: 200; 
} 

奇怪的是第二個DIV中的文本出現在圖像上方,而不是第二個DIV。紅色應該在圖像上,因爲文字是...

有沒有人知道如何解決這個問題?

+1

添加位置:相對。第二。 https://css-tricks.com/almanac/properties/z/z-index/ https://jsfiddle.net/10L7fad9/ – sinisake

回答

1

默認情況下,<div>元件是position: static,其忽略位置CSS包括z-index。將position: relative添加到.second元素允許z-index正常工作。

我也將負餘量更改爲top: -80px,這更清潔。

body { 
 
    text-align: center; 
 
} 
 

 
.first { 
 
    background-color: orange; 
 
    z-index: 100; 
 
} 
 

 
.first img { 
 
    display: block; 
 
    height: auto; 
 
    outline: 0; 
 
    width: 100%; 
 
} 
 

 
.second { 
 
    background-color: red; 
 
    z-index: 200; 
 

 
    position: relative; 
 
    top: -80px; 
 
}
<body> 
 

 
    <div class="first"> 
 
    <img src="http://placehold.it/350x150"> 
 
    </div> 
 

 
    <div class="second"> 
 
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has 
 
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing 
 
    software like Aldus PageMaker including versions of Lorem Ipsum. 
 
    </div> 
 

 

 
</body>

+0

我錯過了......謝謝 –

2

在第二個div position: relative;

+0

加一,尤其是因爲用戶名,哈哈。 – sinisake

+0

加一個在這裏,不是因爲你的名字。我認爲@MiguelMoura是從某種RMT播放器購買的共享帳戶。 – 2016-12-16 19:28:40

1

嘗試相對定位第二DIV:

.second { 
    background-color: red; 
    margin: 0 auto; 
    position:relative; 
    z-index: 200; 
} 
0

你可以用下面的代碼試試:

.second { 
    background-color: red; 
    margin: 0 auto; 
    z-index: 200; 
}