地点DIV比其它DIV和图像

问题描述:

我有以下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

默认情况下,<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

我错过了......谢谢 –

在第二个div position: relative;

+0

加一,尤其是因为用户名,哈哈。 – sinisake

+0

加一个在这里,不是因为你的名字。我认为@MiguelMoura是从某种RMT播放器购买的共享帐户。 – 2016-12-16 19:28:40

尝试相对定位第二DIV:

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

你可以用下面的代码试试:

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