【问题标题】:how to show img behind text with :hover?如何使用:悬停在文本后面显示图像?
【发布时间】:2018-03-10 21:10:14
【问题描述】:

我有一个带有文本的 div,里面有一个链接。在那个文本 div 之后,我有一个带有 img 的 div。现在,我希望当我 :hover 链接时 img 在文本后面产生。当 img div 在文本 div 容器中时,它可以工作,但随后它会在文本上产生。

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

<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>

【问题讨论】:

  • 不清楚你想达到什么目的
  • @TemaniAfif 我想要,如果我将鼠标悬停在链接上,图像 div 将出现在背景中,在文本 div 后面。这就是我设置 z-index 的原因。但是作为背景的图像仅在没有悬停效果的情况下才有效,并且悬停效果仅在图像 div 位于文本 div 内时才有效,然后 z-index 不再起作用。我希望你现在能理解我

标签: html css hover z-index


【解决方案1】:

你可以试试这样的:

#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>

【讨论】:

  • 是的,这就是 CSS 背景的用途。
【解决方案2】:

最好的解决方案是使用 Temani Afif 提出的背景属性。 Hoverwer,如果你想使用&lt;img/&gt; 标签,使用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>

由于#pic#text 内部,并且由于您无法在css 中选择前一个元素,因此您必须使用z-index: -1 来保留您的图像。

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 2013-11-30
    • 2013-07-11
    • 2016-12-23
    • 1970-01-01
    • 2013-10-23
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多