2014-10-05 77 views
2

好的,所以这段代码在div中产生了两个块。顶部块应该越过底部块,因为顶部具有更高的Z-索引,但是当我给底部块留出顶部:-30px时,它会在顶部块之上。z-index没有正确建立索引

<html> 
<head></head> 
<body> 
    <div style="width: 300px; height: 90px; overflow: hidden;"> 
     <div style="width:300px; height: 50px; z-index: 2; background-color: #ff0000;"> 
     </div> 

     <div style="width:300px; height: 50px; z-index: 1; background-color: #ff00ff; margin-top: -30px;"> 
     </div> 
    </div> 
</body> 
</html> 

我该如何获得顶部块去底部块?

+2

(希望这只是用于演示目的,但)你应该避免使用内嵌样式...这是非常困难的工作,与和维护。 – 2014-10-05 19:56:32

回答

4

z-index财产only applies to positioned elements

您可以添加position: relative,它将按预期工作(example)

position属性的默认值是static,这就是为什么它不起作用。

+0

谢谢你的工作!我会尽快接受。 – CyanPrime 2014-10-05 20:01:59

1

在这两个区块的CSS添加position:relative;

<div style="width: 300px; height: 90px; overflow: hide;"> 
     <div style="position: relative; width:300px; height: 50px; z-index: 2; background-color: #ff0000;"> 
     </div> 
     <div style="position: relative; width:300px; height: 50px; z-index: 1; background-color: #ff00ff; margin-top: -30px;"> 
     </div> 
    </div> 

http://jsfiddle.net/uu721kgc/