Home >Web Front-end >CSS Tutorial >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
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!