html - 悬停时显示文本

标签 html css

我想隐藏我的 <h2>元素,直到用户将鼠标悬停在图像上。

因此,当用户将光标移到图像上时,它会在图像上显示“Drinks”一词。我也希望文字居中显示在图片上。

谁能告诉我如何在 CSS 中实现这一点?

演示:https://jsfiddle.net/hj3xrumo/

li {
  list-style-type: none;
  padding: 0;
  margin: 0
}

li h2 {
  position: relative;
  top: 0;
}
<h1>
  Test
</h1>

<li class="product-category product first">
  <a href="#">
    <img src="http://placehold.it/370x370" alt="Drinks" width="370" height="370" />
    <h2 class="woocommerce-loop-category__title">Drinks</h2>
  </a>
</li>

最佳答案

使用 position: absolute;display:none;h2并使其成为display: blockimg:hove

ul {
  padding: 0;
  margin: 0;
}

li {
  list-style-type: none;
  padding: 0;
  margin: 0;
  position: relative;
  display:inline-block;
}

li h2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%);
  display: none;
  margin:0;
}

li a:hover h2 {
  display: block
}
<ul>
  <li class="product-category product first">
    <a href="#">
      <img src="http://placehold.it/370x370" alt="Drinks" width="370" height="370" />
      <h2 class="woocommerce-loop-category__title">Drinks</h2>
    </a>
  </li>
</ul>

关于html - 悬停时显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46172149/

相关文章:

html - XML 到 HTML : outputting literal child nodes

javascript - CSS:x 和 y 上的中心元素

html - h :commandButton with css not the same in IE

html - 如何在div中居中对齐多个span?

CSS : p tag : cannot bold or text-size

html - 在页面上查找元素而不搜索整个文档

html - 在水平导航中均匀分布链接

html - 水平居中具有不同背景图像宽度的列表项

formatting - CSS 行高和填充

html - ol li 中的 float 跨度在 Firefox 中显示正确,但在 Chrome 中显示不正确