So I'm using CSS :hover to replace a submit button background. When I mouse over the button the old background image disappears (so it looks like nothing is there) for a moment and then reappears with the new background. I thought that perhaps the button image file size was too large but its only 1.4kb. Is there a way to prevent this, caching or pre-loading, or something along those lines?
Is this only on the initial page display / hover?
This will be because the image file is only loaded on request - i.e. the hover action.
To avoid this, both button states should be stored in a single file. You then just need to adjust the background-position property to display the correct half of the image for it's current state.
Here's a rough example (note that button.png contains both image states and is 40 pixels high):
button {
background-image: url(button.png);
width: 60px;
height: 20px;
background-position: 0 0;
}
button:hover {
background-position: 0 -20px;
}
It's because it takes time for the "hover" image to download before it displays. To prevent this, you can use a sprite image technique.
You could, maybe, use a technique that's similar in intent, albeit not execution, to Bryn's answer, above.
.button {background-image: url(img/for/hover-state.png)
background-position: top left;
background-repeat: repeat-x;
background-color: #fff;
height: 1.5em;
width: 5em;
}
.button span
{background-image: url(img/for/non-hover-state.png);
background-position: top left;
background-repeat: repeat-x;
background-color: #000;
height: 1.5em;
width: 5em;
}
.button:hover span
{background-color: transparent;
background-image: none;
}
The similarity I mentioned is to have both images present on the document in order to avoid the hover-flicker. On hover of the button the background-image of the span will disappear, and reveal the hover state, rather than having to load it on-demand.
The bonus is that, although I specified the height
/width
above this technique will work for dynamic re-sizing, not relying on fixed-width sizes of images (or it's as fluid as your design can allow it to be).