Home >Web Front-end >CSS Tutorial >How Can I Create Image Hover Overlays Using Only CSS?

How Can I Create Image Hover Overlays Using Only CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 09:32:13410browse

How Can I Create Image Hover Overlays Using Only CSS?

Image Hover Overlays with Pure CSS

Using HTML and CSS, you can add a transparent black overlay to an image when the mouse hovers over it. To achieve this without employing an overlay element, consider using a pseudo element instead.

Wrap the image with the

element:

<div class="image">
  <img src="image.jpg">
</div>

Assign relative positioning and optional dimensions to .image:

.image {
  position: relative;
  width: 200px;  /* Optional */
  height: 200px;  /* Optional */
}

Set the child img element to have a width of 100% and vertical alignment.

.image img {
  width: 100%;
  vertical-align: top;
}

Create a pseudo element to display the overlay:

.image:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 1s;
}

Make the overlay visible on hover:

.image:hover:after {
  opacity: 1;
}

Now, when the cursor hovers over the image, a transparent black overlay will smoothly fade in.

The above is the detailed content of How Can I Create Image Hover Overlays Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn