2013-11-27 51 views
5

我試圖在文本上方放置圖像(而非之前)。以下是我到目前爲止的代碼。我也發佈了我得到的結果和我想要達到的結果。我的目標是,當用戶懸停<p>我想在上面顯示圖片時,這意味着我需要使用絕對位置,因爲我不希望任何其他位置發生任何移動,我只想在圖片上方顯示圖片。如何在內容上方放置圖像

注意:圖像沒有定義高度,它可以更長或更短。

<div id="wrap" style="position:relative; height: 100px; width: 500px; background: red"> 
     <img src="img/cat.png" style="position:absolute; "> 
     <p style="position:absolute; ">Some text here..</p> 
</div> 

這是結果我得到的,

enter image description here

這是我的願望的結果。注意:我不希望任何東西被移動,我只是想在文字懸停後在文字上方顯示圖片,因此我不需要任何東西在任何地方移動。

enter image description here

+0

給出'z-index:1000000;'風格 –

回答

3

工作例如:http://jsfiddle.net/Rhcp5/2/

HTML:

<div id="wrap"> 
     <img src="img/cat.png"> 
     <p>Some text here..</p> 
</div> 

CSS:

#wrap { 
position:relative; 
height: 100px; 
width: 500px; 
background: red; 
} 

#wrap img { 
display: none; 
position: absolute; 
bottom: 100%; 
margin-bottom: 5px; 
} 

#wrap:hover img { 
display: block; 
} 

這將處理可變高度的圖像。

+0

看看我對David Aguirre的回覆,你發佈了相同的答案 – ILikebanana

+0

試試看看。這不是同一個答案。它處理可變高度的圖像。 –

+0

這裏的證明,使用相同的代碼:http://jsfiddle.net/Rhcp5/1/ –

0

給容器「包裝」的「相對」的位置 然後將圖像的位置,你現在跟「絕對」,然後使用負「頂」

<div id="wrap" style="position:relative; height: 100px; width: 500px; background: red"> 
    <img src="img/cat.png" style="position:absolute; "> 
    <p style="position:absolute; ">Some text here..</p> 
</div> 

繼承人的CSS

#wrap { 
    position: relative; 
} 

#wrap img:hover { 
    position: absolute; 
    top: -50px; 
    left: 0; 
} 

如果你不知道圖像的高度,然後使用jquery。未經測試。

var imageHeight = $("#imgID").height(); 
$('#imgID').hover(function() { 
    $('#imgID').css({ 
     'position': 'absolute', 
     'top': '-' + imageHeight, 
     'right': '0' 
    }) 
}); 
+0

這將工作,但如果圖像的高度如此之大,那麼頂部:-50px將無用。就像我說的,圖像沒有定義高度 – ILikebanana

+0

那麼你不應該讓圖像超過特定的高度。使用圖像的「最大高度」,使其不超過某個高度。 –

+0

是真的,但如果我將max-height設置爲100px,並且圖像低於100px(如40px),則圖像將遠離文本。 – ILikebanana