HTML实现图片悬停消失显示下方文本的问题求助
Fixing Image-to-Text Hover Effect
Here's how to adjust your HTML and CSS to get the desired effect—where hovering over the container hides the image and shows the text in its exact place:
Updated HTML
<table align="center" style="width: 90vw; margin: 0 10vw;"> <tr> <th> <div class="inhabitantOne"> <p>Test Text. Test Text. Test Text. Test Text.</p> <img src="judas.jpg" alt="Judas"> </div> </th> <!-- Add more table cells here for additional image/text pairs --> </tr> </table>
CSS Solution
/* Make the container a positioning reference for its children */ .inhabitantOne { position: relative; width: 100%; } /* Ensure the image fills the container properly */ .inhabitantOne img { width: 100%; height: auto; display: block; /* Removes extra space below the image */ } /* Style text to be hidden by default and cover the image area */ .inhabitantOne p { position: absolute; top: 0; left: 0; width: 100%; height: 100%; margin: 0; padding: 1.5rem; box-sizing: border-box; display: none; /* Hide text initially */ background-color: rgba(0, 0, 0, 0.8); /* Dark overlay for text readability */ color: white; text-align: center; /* Center text vertically and horizontally */ display: flex; align-items: center; justify-content: center; } /* Toggle visibility on hover */ .inhabitantOne:hover img { display: none; } .inhabitantOne:hover p { display: flex; /* Show text with flex alignment */ }
Why This Fixes Your Issue
- Relative Container: The
.inhabitantOnediv usesposition: relativeso the text can be positioned exactly over the image. - Overlapping Elements: The text is set to cover the entire container area, matching the image's space perfectly—no more text sitting above the image.
- Hover Toggle: When you hover over the container, we hide the image and show the text, creating a seamless replacement effect.
- Readability: The semi-transparent background ensures your text is easy to read against whatever is behind it.
You can reuse this pattern for other image/text pairs by copying the .inhabitantOne structure (or reuse the class if all pairs need the same styling).
内容的提问来源于stack exchange,提问作者Tfarcraw IIV
相关产品推荐
相关产品推荐

