Prevent CSS image swap from flashing background color?

3490 views css
4

In the code below I'm using CSS for a button background and :hover to swap to a different one.

When the switch happens on the first mouse over it briefly flashes the background color. (I set it to orange here so it's more noticeable, but it does the same, but with white background, if I leave the background color unspecified).

But it does not do it (flash the background color) on subsequent mouse overs.

How can I prevent the first flash of the background color that happens on page load and first mouseover?

https://codepen.io/ClayN/pen/EeeRyP

<body>

<style>

.backgroundbutton {

    background-image:url('http://www.BungalowSoftware.com/images/silver-background.jpg');
    width:100px;
    height:30px;
    background-color:orange;
}

.backgroundbutton:hover {

    background-image:url('http://www.BungalowSoftware.com/images/silver-background2.jpg')
}
</style>

<a class="backgroundbutton">  hover over me</a>

</body>

answered question

What about setting background-color: transparent ??

2 Answers

4

Since the hover background image will not be pre-loaded, so that it shows the flashing effects especially for larger image size and longer loading time.

It can be fixed easily by using CSS sprites, e.g. combine the 2 backgrounds into 1, and change the background-position on :hover:

element {
  background: url("combined.jpg") 0 0 no-repeat;
}

element:hover {
  background-position: 0 -20px; /* x-position y-position */
}

posted this
8

Load both images using multiple background and make the first one on the top then adjust background-size to show the other on hover:

.backgroundbutton {
  background-image: 
   url('http://www.BungalowSoftware.com/images/silver-background.jpg'),
   url('http://www.BungalowSoftware.com/images/silver-background2.jpg');
  background-size:auto;
  width: 100px;
  height: 30px;
  background-color: orange;
}

.backgroundbutton:hover {
  background-size:0 0,auto;
}
<a class="backgroundbutton">  hover over me</a>

posted this

Have an answer?

JD

Please login first before posting an answer.