Overriding CSS background image styles - both images are loaded?

后端 未结 4 655
孤城傲影
孤城傲影 2021-01-11 13:40

If I have 2 CSS styles that assign background images to an element, and one style overrides the other. Will both images be downloaded by the browser or just the overriding o

相关标签:
4条回答
  • 2021-01-11 14:07

    The answer is NO. The first one was overridden won't load the background property. Why? Because browsers load your css file first before loading any other resources. They handle css files first then start loading images based on order and overriding order.

    For example:

    div {
        border: solid 1px #000000;
        background: url('images/sprites.png') no-repeat x y;
    }
    
    .mobile div {
        border: solid 1px #000000;
        background: url('images/sprites_mobile.png') no-repeat x y;
    }
    

    Browsers will process this css for your mobile to become like this:

    div {
        border: solid 1px #000000;
        background: url('images/sprites_mobile.png') no-repeat x y;
    }
    

    And now, browsers already ignored the sprites_mobile.png for loading.

    0 讨论(0)
  • 2021-01-11 14:17

    The overridden image will not be loaded.

    Just to be clear, for example: http://jsfiddle.net/thirtydot/MjKfG/1/show/

    <div id="test">test</div>
    
    div {
        background: url(http://dummyimage.com/600x400/000/fff)
    }
    #test {
        background: url(http://dummyimage.com/200);
        width: 200px;
        height: 200px
    }
    

    Only http://dummyimage.com/200 will be loaded.

    This is true in at least Chrome, Safari, Firefox, IE8/9, Opera.

    I'd guess it's true in all browsers, because it's a simple and effective optimization.

    0 讨论(0)
  • 2021-01-11 14:17

    It seems in some cases the answer is yes:

    http://www.cloudfour.com/css-media-query-for-mobile-is-fools-gold/

    http://www.cloudfour.com/examples/mediaqueries/image-test/#t4

    0 讨论(0)
  • 2021-01-11 14:22

    Can you not do an experiment and view the web log files to see what is happening?

    Otherwise why not have a little PHP to select the appropriate style sheets depending on the device.

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