简体   繁体   中英

Load images only in certains resolutions

I have a header at the top of my page which have two images, one of them is only visible when the viewport is large ( > 940) and the other only showed on mobile. To achieve this behavior, I'm using Bootstrap 3 and their defined sets of media queries:

<header class="container">
   <div class="row">

      <div class="col-lg-4 hidden-xs">
        <img src="img/hi-res-logo.png">
      </div>

      <div class="col-xs-12 visible-xs">
        <img src="img/small-logo.png">
      </div>

  </div>
</header>

So far, no big deal, the previous code does the job well, but what I want is prevent the load of the large image file itself on mobile to avoid unnecessary data consumption... so how to achieve that?

Set image as a background and use media query in CSS.

<div class="container">
    <div class="row">
         <div class="col-lg-4" id="my-div"></div>
    </div>
</div>

CSS

@media (max-width: 700px) {
    #my-div {
        background-image: url('img/small-logo.png');
    }
}
@media (min-width: 700px) {
    #my-div {
        background-image: url('img/hi-res-logo.png');
    }
}
**I think it is better to use single media query in this case.**   
#my-div {
    background-image: url('img/hi-res-logo.png.png');
    width: 100px; /*image width - please change as per your image*/
    height: 100px; /*image height - please change as per your image*/
}
@media (min-width: 700px) {
   #my-div {
       background-image: url('img/small-logo.png');
       width: 200px; /*image width - please change as per your image*/
       height: 200px; /*image height - please change as per your image*/
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM