Clay Nichols
Clay Nichols

Reputation: 12139

Prevent background image flashing on change

I'm using background image for a button and switch to a different one on :hover.

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, it does the same with white background, or if I leave the background color unset). However, it does not flash on subsequent mouseovers.

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

.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')
}
<a class="backgroundbutton">hover over me</a>

Upvotes: 2

Views: 2572

Answers (2)

Stickers
Stickers

Reputation: 78686

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 background images into 1, and change the background-position on :hover, say the new image is 400px (200+200) height.

And, don't set any background-color to stop the initial flashing of the background color on page load. Also, width and height won't apply to inline-level a tag unless you change it to display: inline-block or block etc.

.backgroundbutton {
  background: url("https://i.sstatic.net/GATzU.png") 0 0 no-repeat;
}

.backgroundbutton:hover {
  background-position: 0 -200px;
}
<a class="backgroundbutton">hover over me</a>

In addition, you don't need any images for gradient background, e.g.:

.backgroundbutton {
  background: linear-gradient(to right, #999, #fff);
}

.backgroundbutton:hover {
  background: linear-gradient(to right, #ccc, #fff);
}
<a class="backgroundbutton">hover over me</a>

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272955

Load both images using multiple background and make the first one on the top then adjust background-size to show the other on hover. In this case, both images will be loaded initially and the second one will be ready 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>

Upvotes: 5

Related Questions