如何在悬停时在图像上进行覆盖

How to make an overlay on image when hovered?

本文关键字:覆盖 悬停 图像      更新时间:2024-02-21

我有一个div,里面有img。Div边界稳固。当悬停覆盖图像时,我需要div的背景,并且覆盖的中心应该有一个文本。

这是我的代码:

    <div class="picture">
<a href="product-link"><img src="product-img-link" /></a>
</div>

我该怎么做?最简单的方法是什么?

谢谢你的帮助。

这样做:

编辑:添加了垂直居中的文本太

HTML

.picture {
  position: relative;
  width: 400px;
  text-align: center;
  border: 1px solid #000;
}
.overlay {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #eee;
  line-height: 100%;
}
.vertical-center {
  display: table;
  width: 100%;
  height: 100%;
  text-align: center;
}
.vertical-center span {
  display: table-cell;
  vertical-align: middle;
}
.picture:hover > .overlay {
  display: block;
  opacity: .8;
}
<div class="picture">
  <div class="overlay">
    <div class="vertical-center">
      <span>Some text</span>
    </div>
  </div>
  <a href="product-link">
    <img src="https://grd.me/m/img/logo.png" />
  </a>
</div>

您可以执行以下操作:html:

<div class="picture">
    <a href="product-link"><img src="path" /></a>
    <div class="cover">
       cover
    </div>
</div>

css:

body{
  margin:0px;
}
.picture{
 position;relative;
 width:400px;
 height:250px;    
}
.picture img{
 width:100%;
 height:100%;
}
 .cover{
 display:none;
 position:absolute;
 top:0px;
 left:0px;
 background-color:green;
 height:250px;
 width:400px;
}
.picture:hover .cover{
  display:block;
}

演示:小提琴

类似的东西?

.flex-div {
  display: flex;
  width: 240px;
  height: 240px;
  justify-content: center;
  align-items: center;
  border: solid 1px gray;
  background-image: url('http://i01.i.aliimg.com/wsphoto/v0/680934765/100-cotton-soft-outsole-baby-font-b-tiger-b-font-cartoon-skidproof-toddler-newborn-font-b.jpg');
  background-size: cover;
}
.flex-div a{
  font-family: 'Oswald', sans-serif;
  font-size: 24px;
  font-weight: bold;  
  text-decoration: none;
  color: white;
  padding: 10px 16px 10px 16px;
  background-color: rgba(40, 255, 40, 0.6);
  border-radius: 8px;
  opacity: 0;
  -webkit-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.flex-div:hover a{
  opacity: 1.0;
}
<div class='flex-div'><a href='#'>Click to get it!</a></div>

查看

    <div class="picture">
    <a href="#" class="product_slogan">
        Product Link Text
    </a>
    <img src="product-img-link" />
</div>
.picture{
    width:300px;
    height: 350px;
    background-color:red;
    position:relative;
}
.product_slogan{
    position: absolute;
    width:100%;
    height:100%;
    text-align:center;
    background-color:rgba(0,0,0,0.5);
    opacity:0;
    color:#fff;
     -webkit-transition: opacity 0.4s ease-in-out;
    -moz-transition: opacity 0.4s ease-in-out;
    -o-transition: opacity 0.4s ease-in-out;
    transition: opacity 0.4s ease-in-out;
}
.picture:hover .product_slogan{
    opacity:1
}

https://jsfiddle.net/ryc0x6ws/1/