Home > Web Front-end > CSS Tutorial > Can CSS Create a Transparent Black Overlay on Image Hover?

Can CSS Create a Transparent Black Overlay on Image Hover?

Linda Hamilton
Release: 2024-12-10 16:44:11
Original
373 people have browsed it

Can CSS Create a Transparent Black Overlay on Image Hover?

Black Transparent Overlay on Image Hover Using CSS: An In-Depth Approach

Query:

Can I create a transparent black overlay that appears when hovering over an image using only CSS?

Response:

Yes, you can achieve a transparent black overlay effect on image hover using CSS. Here's how:

Alternative Approach Using Pseudo Elements:

Instead of using an overlay element, you can leverage a pseudo element on the image. This method improves responsiveness and versatility:

HTML:

<div class="image">
    <img src="image.jpg" alt="" />
</div>
Copy after login

CSS:

.image {
  position: relative;
  /* Optional dimensions */
}

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

.image:after {
  content: '\A';
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.6);
  opacity: 0;
  transition: all 1s;
}

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

Explanation:

  • position: relative on the .image element allows the pseudo element to position itself relative to its parent.
  • vertical-align: top fixes the baseline alignment on the image.
  • The :after pseudo element creates the overlay with absolute positioning and a black semi-transparent background.
  • An opacity transition is applied for a smooth transition on hover.

Adding Text on Hover (Optional):

To display text on hover, set the content property of the pseudo element to the desired text:

.image:after {
  content: 'Hover Text';
  /* Other styling... */
}
Copy after login

The above is the detailed content of Can CSS Create a Transparent Black Overlay on Image Hover?. 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