CSS Sprites中background-position作用机制及链接hover变色问题咨询
Hey there! Let's unpack your two core questions using the code you shared—it's a perfect example of how CSS sprites work for interactive buttons.
1. How does background-position create the "animation" effect?
This relies on CSS Sprites—a smart technique where multiple button states (normal, hover, active) are combined into one single image file. Instead of loading separate images for each state, we just shift which section of the sprite is visible using background-position. Here's the play-by-play for your code:
- First, the
.buttonclass sets a fixedheight: 36pxand assigns the sprite image (button-sprite.jpg) as the background. It usestext-indent: -9999pxto hide the button text (so only the background image shows) anddisplay: inline-blockto let the anchor element accept width/height values (since anchor tags are inline by default and don't support these properties otherwise). - The sprite image itself is structured in rows:
- Top row (vertical position
0px): Normal state of both buttons.#add-to-basketusesbackground-position: 0px 0pxto show the left 174px slice of the sprite, while#framing-optionsuses-175px 0pxto shift left by 175px (revealing the second button on the top row). - Middle row (vertical position
-40px): Hover state. When you hover over#add-to-basket,background-position: 0px -40pxshifts the background upward by 40px, showing the hover version of that button from the middle row of the sprite. The same logic applies to#framing-options:hover. - Bottom row (vertical position
-80px): Active state (when the button is clicked). Shifting upward by 80px reveals the active-state button from the bottom row of the sprite.
- Top row (vertical position
Since we're only adjusting the background position (not loading new images), the state change feels instant—like a smooth "animation"—it's just showing a different slice of the same image file.
2. Why does the anchor element turn green on hover?
Looking at your code, there's no color property set for the anchor tags—and text-indent: -9999px already pushes the button text way off-screen (you can't actually see it). The "green" you're noticing is part of the hover-state image in the sprite file.
When you hover, background-position shifts to display the middle row of the sprite, which presumably has green-colored versions of the buttons. The text itself isn't changing color—you're just seeing the hover-state background image instead of the normal one.
Quick Recap of Key Code Snippets
- Hiding text while keeping it accessible for screen readers:
text-indent: -9999px; - Enabling width/height on anchor tags:
display: inline-block; - Shifting sprite positions for interactive states:
a#add-to-basket:hover { background-position: 0px -40px; }
内容的提问来源于stack exchange,提问作者Arturo Abreu

