2014-04-02 54 views
0

我在div中有兩個圖像。相同的寬度/高度以及懸停時顯示次要元素的效果。但是,輔助圖像在第一個圖像之前顯示,不是預期的行爲。使相對元素出現在絕對元素相同的容器之前

的CSS:

.div-container { 
    position: relative; 
} 

.div-container img.primary { 
    position: relative; 
} 

.div-container img.secondary { 
    position: absolute; 
    top: 0; 
    left: 0; 
    transition: opacity 1s ease-in-out; 
} 

.div-container img.secondary:hover { 
    opacity: 0; 
} 

的HTML:

<div class="div-container"> 
    <img class="primary"> 
    <img class="secondary"> 
</div> 

問題:我想先顯示主圖像。

實施例:​​

+0

z-index是你在找什麼! – Gadgetster

+0

我曾試過所有元素的z-index,但顯然沒有奏效。 –

+0

http://jsfiddle.net/A6y7Y/2/ – Gadgetster

回答

0

我解決了這個問題。

出於某種原因,將opacity: 0設置爲徘徊的圖像,使其首先出現。 我所做的只是將次映像設置爲opacity: 0,並將容器分區與opacity: 1(而不是徘徊的映像)懸停在一起。我還將z-index包含在兩個圖像中,並且索引較高的輔助圖像。在我使用的代碼下面,希望它可以幫助未來的人。

.div-container { 
    position: relative; 
} 

.div-container img.primary { 
    position: relative; 
    z-index: 5; 
} 

.div-container img.secondary { 
    position: absolute; 
    top: 0; 
    left: 0; 
    opacity: 0; 
    z-index: 6; 
    transition: opacity 1s ease-in-out; 
} 

.div-container:hover img.secondary { 
    opacity: 1; 
} 
0

既可以使用z-index和改變對:hover效果的值或者僅僅容易地切換圖像。但是你應該在這裏尋找的是將它們放在一個文件中,並像CSS一樣控制背景圖像的位置。 Here is a good example

+0

嗨安德烈。 z-index沒有工作,使用精靈不是一個解決方案,因爲我無法控制圖像。 –

0

交換中小學css樣式的CSS樣式和z指數主要添加爲1要解決這個問題

HTML

`<div class="div-container"> 
    <div class="primary">Layer1</div> 
    <div class="secondary">Layer2</div> 
</div>` 

CSS

`.div-container { 
    position: relative; 
} 
.div-container div{ 
    width:100px;`enter code here` 
    height:100px; 
    border:1px solid red; 
} 
.div-container .secondary { 
    position: relative; 
    background-color: blue; 
} 

.div-container .primary { 
    position: absolute; 
    top: 0; 
    left: 0; 
    transition: opacity 1s ease-in-out; 
    background-color: #ccc; 
    z-index:1; 
} 

.div-container .primary:hover { 
    opacity: 0; 
}` 
+0

該代碼工作,但它截斷旁邊的圖像 –

+0

你可以用小提琴示例顯示它,所以它會更好地理解清楚 – SagarPPanchal

+0

http://jsfiddle.net/A6y7Y/ –

相關問題