在悬停时显示图像,在背景中居中

2022-01-22 00:00:00 image hover html css

我在 Stackoverflow 上遇到了许多关于在悬停时显示图像的问题,但找不到解决我的问题的方法.

I went through a number of questions regarding displaying image on hover here on Stackoverflow, but couldn't find a solution for my problem.

现在,当我将鼠标悬停在段落的背景上时,我设法在该段落的背景中显示了一张图片.查看 JSFiddle.

Right now I managed to display an image in the background of the paragraph once I hover on it. See on JSFiddle.

理想情况下,我想实现什么:一旦我将鼠标悬停在段落内的 Example1 上,我想在背景中显示 Image1,而不是在段落下方,而是在背景中居中,在所有元素下方.如图所示.

Ideally what would I like to do achieve: once I hover over an Example1 inside of a paragraph I would like to display Image1 in the background, not below the paragraph, but centered in the background, below all of the elements. As pictured here.

将鼠标悬停在 Example2 上会显示 Image2,Example3 会显示 Image3.

Hovering on Example2 would ideally display Image2, and Example3 would display Image3.

HTML

<div id="imgbg">
<p>Portfolio:</p>    
<p>I worked with:<br />
Example1, Example2, Example3, Example4, Example5
</p>
</div>

CSS

#imgbg {
height: 100%;
width: 100%;
}

#imgbg:hover {
background-image: url('http://i.imgur.com/9bbjE1Mb.jpg');
}

有人有解决办法吗?非常感谢.

Does anyone have a solution? Many thanks.

推荐答案

希望对你有帮助.

#imgbg {
  position: relative;
  width: 100%;
  height: 265px;
}

#imgbg .Example:hover:after {
  display: block;
}

#imgbg .Example:after {
  content: '';
  display: none;
  width: 160px;
  height: 160px;
  background: url('http://i.imgur.com/9bbjE1Mb.jpg');
  background-size: contain;
  position: absolute;
  top: 50%;
  left: 0;
  margin-top: -80px;
  margin-left: 145px;
  z-index: -1;
}

<div id="imgbg">
  <p>Portfolio:</p>    
  <p>I worked with:<br />
   <span class="Example">Example1</span>,
   <span class="Example">Example2</span>,
   <span class="Example">Example3</span>,
   <span class="Example">Example4</span>,
   <span class="Example">Example5</span>
  </p>
</div>

相关文章