Caption overlay on hover

2019-08-30 01:18发布

问题:

I'm trying to achieve a simple caption that appears over my thumbnail images upon hover. The intention is to have the image by itself, then on hover, the image fades out a little, with the caption fading into view above.

The problem I'm having is that the hover works fine until the mouse goes over the caption itself, which then returns the image to 100% opacity

<a href="#" class="thumbnail">

  <img src="img/placeholder1.jpg" alt="...">
  <span>caption</span>
</a>

CSS

a.thumbnail {
border:none;
border-radius: none;
padding:0;
margin:0;
position: relative;
background: #222;
}

a.thumbnail img {
-webkit-transition: opacity 0.5s ease;
-moz-transition: opacity 0.5s ease;
-o-transition: opacity 0.5s ease;
transition: opacity 0.5s ease;
opacity: 1; 
}


a.thumbnail img:hover {

opacity: 0.7;
}


a.thumbnail span {
color: #FFF;
position: absolute;
bottom: 40%;
width: 100%;
height: 20%;
padding: 10px;
opacity: 0; 
-webkit-transition: opacity 0.5s ease;
-moz-transition: opacity 0.5s ease;
-o-transition: opacity 0.5s ease;
transition: opacity 0.5s ease;
}

a.thumbnail:hover span {
opacity: 1; 
}

回答1:

Move the image hover to the parent div. In this way the opacity will remain when hovering over the caption as you would still be hovering over the parent.

   a.thumbnail:hover img {
      opacity: 0.7;
    }

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
a.thumbnail {
  border: none;
  border-radius: none;
  padding: 0;
  margin: 0;
  position: relative;
  background: #222;
}
a.thumbnail img {
  -webkit-transition: opacity 0.5s ease;
  -moz-transition: opacity 0.5s ease;
  -o-transition: opacity 0.5s ease;
  transition: opacity 0.5s ease;
  opacity: 1;
}
a.thumbnail:hover img {
  opacity: 0.7;
}
a.thumbnail span {
  color: #FFF;
  position: absolute;
  bottom: 40%;
  left: 0;
  width: 100%;
  padding: 10px;
  background: red;
  opacity: 0;
  -webkit-transition: opacity 0.5s ease;
  -moz-transition: opacity 0.5s ease;
  -o-transition: opacity 0.5s ease;
  transition: opacity 0.5s ease;
}
a.thumbnail:hover span {
  opacity: 1;
}
<a href="#" class="thumbnail">

  <img src="http://lorempixel.com/output/city-q-c-200-200-4.jpg" alt="..." />
  <span>caption</span>
</a>