基于jQuery实现悬停按钮切换指向图片及居中的问题
Hey there! First off, you made the right call going with .hover() instead of tracking mouse coordinates—this approach is way cleaner and more reliable. You don’t have to mess with calculating X/Y positions or worrying about edge cases where the cursor might be near a button but not quite on it. Binding directly to the button’s hover state is exactly the way to go here.
Now, let’s tackle that image centering problem. Looking at your CSS, the issue is almost certainly with how your image containers or the images themselves are styled. Here are a few targeted fixes you can try:
Fix 1: Use Flexbox (Most Recommended)
Flexbox is the easiest way to center elements both horizontally and vertically. Update your container and image styles like this:
/* Target the list item that holds your image */ .cifre-clasa > ul > li { /* Keep your existing styles: opacity: 0; margin: 5px; */ display: inline-flex; /* Replace inline-block with inline-flex */ justify-content: center; /* Center horizontally */ align-items: center; /* Center vertically */ /* Add a fixed width/height if your container doesn't already have one, e.g.: width: 80px; height: 80px; */ } /* Make sure the image behaves nicely inside the container */ .cifre-clasa > ul > li > a > img { width: 85%; /* Keep your existing size, or use max-width: 100% to prevent overflow */ object-fit: contain; /* Stop the image from stretching or squishing */ }
Fix 2: Absolute Position + Transform
If flexbox isn’t an option for some reason, you can use absolute positioning to center the image:
.cifre-clasa > ul > li { position: relative; /* Set parent to relative so absolute positioning works */ /* Keep your existing styles: opacity: 0; margin: 5px; display: inline-block; */ width: 80px; /* Add a fixed width */ height: 80px; /* Add a fixed height */ } .cifre-clasa > ul > li > a > img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* Shifts image left/up by half its own size */ width: 85%; }
Fix 3: Check for Padding/Margin Interference
Sometimes default padding or margin on containers throws off centering. Add box-sizing: border-box to ensure padding doesn’t expand your container’s size:
.cifre-clasa > ul > li { box-sizing: border-box; padding: 0; /* Clear any default padding */ margin: 5px; /* Keep your existing margin */ }
Quick Troubleshooting Tips
If none of the above work, double-check:
- Does your image have extra white space around it? Open it in an editor and crop any unused area.
- If you’re using inline-block for the container, does
line-heightmatch the container’s height? That can affect vertical alignment too.
内容的提问来源于stack exchange,提问作者Andrei Daniel

