Search code examples
htmlcssopacity

How to create a dark fade + text on image hover?


Having trouble trying to get a certain effect going on:

I have an image. I want to hover over it. It should turn a little black and have some text pop up.

Here is an example

example ^

What's the easiest/simplest setup to do this? Preferably only HTML and CSS

Note: The element needs a background-image being set in CSS.

    .thumbnail {
    background-image: url(potato.jpeg);
    height: 400px;
    width: 450px;
}

.thumbnail:hover {
    background: rgb(0, 0, 0);
    height: 400px;
    width: 450px;
    opacity: 0.5;
    transition: 0.8s;
}

\

<!DOCTYPE html>
<html>

<head>

<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">

</head>

<body>

<div class="thumbnail"> </div>

</body>

</html>

Solution

  • You should use a seperate element for the overlay, in my example a child element. Only the hover status is visible, the regular status isn't, due to opacity: 0

    .thumbnail {
      background-image: url(https://placehold.it/450x400/fa0);
      height: 400px;
      width: 450px;
    }
    .overlay {
      background: rgb(0, 0, 0);
      height: 400px;
      width: 450px;
      opacity: 0;
      transition: 0.8s;
    }
    .thumbnail:hover .overlay {
      opacity: 0.5;
    }
    <div class="thumbnail"><div class="overlay"> </div> </div>

    It becomes a bit more complex when text is involved which should have no opacity at all: In the following example the overlay element has a semi-transparent background-color and gets opacity: 1 when the parent is hovered. That way the text has no opacity when hovered, but the background still has due to its own opacity setting of 0.5:

    .thumbnail {
      background-image: url(https://placehold.it/450x400/fa0);
      height: 400px;
      width: 450px;
    }
    .overlay {
      background: rgba(0, 0, 0, 0.5);
      height: 400px;
      width: 450px;
      opacity: 0;
      transition: 0.8s;
      font-size: 36px;
      color: #fff;
    }
    .overlay:hover {
      opacity: 1;
    }
    <div class="thumbnail"><div class="overlay">SOME TEXT</div></div>