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
Release: 2024-12-15 09:32:13
Original
418 people have browsed it

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>
Copy after login

Assign relative positioning and optional dimensions to .image:

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

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

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

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;
}
Copy after login

Make the overlay visible on hover:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template