如何为已实现的三列图片添加无JS鼠标悬停文字覆盖效果?
Hey there! I see you've got a solid flex-based three-column image grid already—nice work. The key to adding those hover overlays (like the effect you're targeting) is adjusting your HTML structure to include an overlay layer alongside each image, then styling it with CSS to show on hover. Let's break this down step by step.
Step 1: Update Your HTML Structure
Each image needs a parent container to hold both the image and its overlay text. This lets us position the overlay directly on top of the image. Here's how to modify your existing HTML:
<div class="row"> <div class="column"> <div class="image-container"> <img src="https://i.imgur.com/LBFnJzd.gif" style="width:100%" class="hover"> <div class="overlay"> <div class="text">First Image Text</div> </div> </div> </div> <div class="column"> <div class="image-container"> <img src="https://i.imgur.com/eOrPIjL.png" style="width:100%" class="hover"> <div class="overlay"> <div class="text">Second Image Text</div> </div> </div> </div> <div class="column"> <div class="image-container"> <img src="https://i.imgur.com/HWi1rPW.png" style="width:100%"> <div class="overlay"> <div class="text">Third Image Text</div> </div> </div> </div> </div>
Step 2: Add & Adjust CSS for Overlays
Keep all your existing CSS, then add these new styles to enable the hover effect. We'll also tweak your column styles to ensure three perfectly equal columns:
/* Adjust column to fit three equal-width columns */ .column { -ms-flex: 33.33%; /* IE10 */ flex: 33.33%; max-width: 33.33%; padding: 0 4px; } /* Container to hold image and overlay */ .image-container { position: relative; width: 100%; overflow: hidden; } /* Overlay layer (hidden by default) */ .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; transition: .5s ease; background-color: rgba(0, 0, 0, 0.7); /* Semi-transparent black */ } /* Show overlay when hovering the container */ .image-container:hover .overlay { opacity: 1; } /* Centered overlay text */ .text { color: white; font-size: 20px; font-family: 'Sunflower', sans-serif; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }
Quick Explanation of Key Styles
.image-container: Usesposition: relativeso the overlay (which usesposition: absolute) stays anchored to the image, not the entire page..overlay: Starts fully transparent (opacity: 0) and transitions smoothly to visible when you hover over the container. The semi-transparent background ensures text stays readable over any image..text: Usestransform: translate(-50%, -50%)to perfectly center the text vertically and horizontally on the image—no messy margin calculations needed!
Feel free to tweak the overlay color, text size, transition speed, or any other values to match your site's design.
内容的提问来源于stack exchange,提问作者Jae-Gyeong Elissa Ahn

