显示悬停时的文字

时间:2017-09-12 09:00:31

标签: html css

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

因此,当用户将光标移动到图像上时,它会显示“饮料”字样。在图像上。我也希望文字以图片为中心。

有人可以告诉我如何在CSS中实现这个目标吗?

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

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

li h2 {
  position: relative;
  top: 0;
}
&#13;
<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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

添加此

h2{
  display:none;
}
img:hover ~ h2{
  display:block;
}

更新了小提琴(https://jsfiddle.net/hj3xrumo/1/)。

答案 2 :(得分:0)

使用img + h2 +用于下一个孩子

&#13;
&#13;
li {
list-style-type: none;
    padding: 0;
    margin: 0;
    display: inline-block;
    position: relative;
}
li h2 {
  position:relative;
  top:0;
}
.woocommerce-loop-category__title{
display:none;
}
img:hover + .woocommerce-loop-category__title{
display:block;
position: absolute;
    top: 50%;
    width: 100%;
    text-align: center;
    transform: translateY(-50%);
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

检查这是否有效

&#13;
&#13;
Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as  standard input.
&#13;
li {list-style-type:none;padding:0;margin:0;width:370px;height:370px;position:relative;}
li a h2{
position:absolute;
top:40%;
left:40%;
trasnform:translate(-50%,-50%);
text-align:center;}
.imgbox:hover + h2{
  visibility:hidden
}
&#13;
&#13;
&#13;