CSS :hover伪类故障:悬停链接无法显示隐藏图片
Hey there! Let's break down why your hover effect isn't working and how to fix it.
The Root Problem
Your CSS uses the adjacent sibling selector (+), which only targets elements that are the immediately next sibling of the hovered element. Looking at your HTML structure:
<div id="underTitle"> <h2><a href="index.html">Welcome to my Homepage</a></h2> <img id="logovAlign" ...> </div>
The <a> tag is nested inside an <h2>, so the <img> is a sibling of the <h2>, not the <a>. Your selector #underTitle a:hover+#logovAlign is trying to find an <img> that comes directly after the <a>—which doesn't exist in your structure.
Additionally, the color: #009999; rule in that selector does nothing for an <img> element, so you can safely remove it.
Solution 1: Adjust the CSS Selector (No HTML Changes)
Since the <img> is a sibling of the <h2> that contains your link, you can target the <h2>'s hover state instead:
#underTitle { white-space: nowrap; font-size: 20px; color: white; padding: 50px; position: absolute; top: 20%; left: 50%; transform: translate(-50%, -50%); } #underTitle a { color: #ffffff; text-decoration: none; transition: 1s; } #logovAlign { position: absolute; top: 100%; left: 50%; transform: translate(-50%, -50%); opacity: 0; transition: opacity 1s; /* Add this for smooth fade-in */ } /* Updated selector to target h2 hover */ #underTitle h2:hover + #logovAlign { opacity: 1; } /* Keep your link color transition */ #underTitle a:hover { color: #009999; }
This way, when you hover over the <h2> (which includes your link), the adjacent <img> will fade in. I also added a transition to the <img> to make the fade effect smooth, matching your link's transition.
Solution 2: Restructure Your HTML (If You Prefer Hovering Only the Link)
If you want the image to only show when hovering exactly the link text (not the entire <h2>), you can adjust your HTML to make the <a> a sibling of the <img>:
<div id="underTitle"> <a href="index.html"><h2>Welcome to my Homepage</h2></a> <img src="images/faviconp.png" width="50" height="50" alt="Lighting Bolt Logo" id="logovAlign"> </div>
Then your original selector will work (with the unnecessary color rule removed):
#underTitle a:hover + #logovAlign { opacity: 1; }
Either approach will get your hover image working as expected!
内容的提问来源于stack exchange,提问作者JShepherd

