使用CSS根据浏览器宽度加载不同大小的背景图像?

时间:2016-05-19 21:47:08

标签: html css

我有一个页面,我希望根据显示端口的宽度加载不同的图像作为背景。我理解如何使用图片标记和常规图像的srcset标记,但我想知道在处理标记的背景图像时是否有办法做到这一点? 我目前使用的CSS是

1. be able to test out an http/2 client
2. follow a wireshark trace to understand the protocol better

3 个答案:

答案 0 :(得分:1)

您可以使用媒体查询

例如:

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);
    }
}

答案 1 :(得分:1)

使用媒体查询,但同时为它们提供上限和下限。否则,即使只显示一个图像,也将加载所有图像。这样,只会加载一个图像,这样可以节省带宽和加载时间:

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);
  }
}

答案 2 :(得分:0)

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

相关问题