简体   繁体   English

如何用:hover在文本后面显示img?

[英]how to show img behind text with :hover?

i have a div with a text with a link inside. 我有一个div,其中的文本带有链接。 after that text div, i have a div with an img. 在该文本div之后,我有一个带有img的div。 now, i want that when i :hover the link the img spawns behind the text. 现在,我希望当我:hover链接时,img在文本后面生成。 when the img div is in the text div container it works, but then it spawns over the text. 当img div位于文本div容器中时,它可以工作,但是会在文本上方生成。

html html

<body>

<div id="text">
text with a <a id="link">hover me link</a>
</div>

<div id="pic">
<img src="pic.jpg"/>
</div>

</body>

css 的CSS

<style type="text/css">
#text {
    position: absolute;
    z-index:2;
    }

#pic {
    display:none;
    position:fixed;
    top:10px;
    left:20px;
    z-index:1;
}

#link:hover ~ #pic {
    display:block;
}
</style>

You may try something like this: 您可以尝试如下操作:

 #link:before { content:url(https://lorempixel.com/400/200/); position:fixed; z-index:-1; top:0; left:0; display:none; } #link:hover::before { display:block; } 
 <div id="text"> text with a <a id="link">hover me link</a> </div> 

The best solution is to use the background property as propsed by Temani Afif. 最好的解决方案是使用Temani Afif建议的背景属性。 Hoverwer, if you want to use the <img/> tag, there is a tricky way using z-index: -1 . 气垫船,如果您想使用<img/>标记,则使用z-index: -1是一种棘手的方法。

 #pic { position: absolute; top: 0; left: 0; display: none; background: red; height: 100px; width: 100px; z-index: -1; } #text, #link { position: relative; } #link:hover + #pic { display: block; } 
 <div id="text"> text with a <a id="link">hover me link</a> <img id="pic" src="https://lorempixel.com/400/200"/> </div> 

Since #pic is inside #text and since you cannot select previous element in css you must use z-index: -1 to keep your image behind. 由于#pic#text并且由于无法在CSS中选择上一个元素,因此必须使用z-index: -1来保留图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM