Home >Web Front-end >CSS Tutorial >How to Create a CSS Invisible Black Overlay on Image Hover Using Pseudo-Elements?

How to Create a CSS Invisible Black Overlay on Image Hover Using Pseudo-Elements?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 10:03:10751browse

How to Create a CSS Invisible Black Overlay on Image Hover Using Pseudo-Elements?

CSS Invisible Black Overlay on Hover

Achieving a transparent black overlay on an image upon hover is indeed possible using pure CSS. However, the approach mentioned in your initial code sample, involving using an overlay div, may not be suitable due to issues with positioning and visibility.

A more effective solution involves utilizing a pseudo-element. Here's how it works:

CSS Code

.image {
  position: relative;
  /* Set dimensions as needed (or omit for responsiveness) */
  width: 400px;
  height: 400px;
}

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

.image:after {
  content: '\A'; /* Pseudo content to trigger browser rendering */
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.6); /* Black with 60% opacity */
  opacity: 0; /* Initially invisible */
  transition: all 1s; /* Animation transition */
}

.image:hover:after {
  opacity: 1; /* Shows overlay on hover */
}

Explanation

  1. We use a div with class "image" to wrap the image. It's positioned relatively to allow the pseudo-element to be positioned within its bounds.
  2. We style the child img element to have a width of 100% and vertical alignment to the top.
  3. The pseudo-element (.image:after) is positioned absolutely within the image div. It's given an opacity of 0 initially, making it invisible.
  4. On hover (.image:hover:after), the pseudo-element's opacity changes to 1, making it visible and effectively creating the black overlay.

Additional Features

Text Addition:
To add text to the overlay on hover, you can use the content property within the pseudo-element's style. For instance:

.image:after {
  content: 'Hover Text...'; /* Custom overlay text */
}

Customization:
You can adjust the opacity and transition speed to modify the visibility effect. Additionally, you can add background images or gradients to create more complex overlays.

The above is the detailed content of How to Create a CSS Invisible Black Overlay on Image Hover Using Pseudo-Elements?. 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