Prevent background image flashing on change

后端 未结 2 404
难免孤独
难免孤独 2021-01-27 17:19

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 bac

相关标签:
2条回答
  • 2021-01-27 17:42

    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.imgur.com/lrlOvEP.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>

    0 讨论(0)
  • 2021-01-27 18:02

    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>

    0 讨论(0)
提交回复
热议问题