简体   繁体   中英

Loading different sized background images based on browser width using CSS?

I have a page that I would like to have different images load as the background based on the width of the display port. I understand how to do it with the picture tag and the srcset tags for regular images but I'm wondering if there is a way to do it when working with the background image of a tag? The css that I am currently using is

body{
background-image:url(/Content/Images/CloudGradient_480.jpg);
background-repeat:no-repeat;
background-size:cover;
background-position:center;
}

You can use media query

For example:

body{
    background-image:url(/Content/Images/CloudGradient_1280.jpg);
    background-repeat:no-repeat;
    background-size:cover;
    background-position:center;
}

@media max-width: 500px {
    body {
        background-image:url(/Content/Images/CloudGradient_480.jpg);
    }
}
@media max-width: 700px {
    body {
        background-image:url(/Content/Images/CloudGradient_680.jpg);
    }
}

Use media queries, but give them both an upper and a lower limit. Otherwise all the images are going to be loaded, even if only one is displayed. This way, only one image will be loaded, which saves bandwidth and loading time:

body {
  background-repeat:no-repeat;
  background-size:cover;
  background-position:center;
}

@media screen and (min-width: 480px) and (max-width: 800px) {
  body {
    background-image:url(/Content/Images/CloudGradient_800.jpg);
  }
}
@media screen and (min-width: 801px) and (max-width: 1200px) {
  body {
    background-image:url(/Content/Images/CloudGradient_1200.jpg);
  }
}
@media screen and (min-width: 1200px) {
  body {
    background-image:url(/Content/Images/CloudGradient_2000.jpg);
  }
}

使用CSS media queries尝试一下,对于不同的屏幕或端口大小,您将拥有不同的背景图片。

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