如何根据屏幕尺寸提供适当的背景图像尺寸?

时间:2017-05-02 12:45:53

标签: html css twitter-bootstrap

我有一个div:

<div id="ibanners-home" class="ibanners-wrapper"></div>

使用以下css:

#ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner.jpg") no-repeat scroll center top;
    height: 500px;
    min-width: 1200px;
    width: 100%;

现在横幅为所有屏幕加载1920x500图像。 我想有3个图像版本:1366x500,1600x500,1920x500,将根据屏幕分辨率加载。 我该怎么做?

4 个答案:

答案 0 :(得分:2)

您可以将mediaquery用于此

#ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner_1366.jpg") no-repeat scroll center top;
}

@media (min-width:1366px) { 
    #ibanners-home {
        background: rgba(0, 0, 0, 0) url("/images/main-banner_1600.jpg") no-repeat scroll center top;
    }
}   
@media (min-width:1600px) { 
    #ibanners-home {
        background: rgba(0, 0, 0, 0) url("/images/main-banner_1920.jpg") no-repeat scroll center top;
    }
}   

答案 1 :(得分:0)

使用css媒体查询

#ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner1920x500.jpg") no-repeat scroll center top;
    height: 500px;
    min-width: 1200px;
    width: 100%;
}
@media  (max-width: 768px) {
  #ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner1366x500.jpg") no-repeat scroll center top;
  }
}
@media  (min-width: 769px) and (max-width: 900px) {
  #ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner1600x500.jpg") no-repeat scroll center top;
  }
}
@media  (min-width: 901px) {
  #ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner.jpg") no-repeat scroll center top;
  }
}

答案 2 :(得分:0)

#ibanners-home {
    height: 500px;
    min-width: 1200px;
    width: 100%;
}
@media (min-width: 1920) {
    #ibanners-home {
        background: rgba(0, 0, 0, 0) url("/images/main-banner1920.jpg") no-repeat scroll center top;
}
@media (min-width: 1600) and (max-width: 1919) {
#ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner1600.jpg") no-repeat scroll center top;
}
@media (max-width: 1599) {
#ibanners-home {
    background: rgba(0, 0, 0, 0) url("/images/main-banner1366.jpg") no-repeat scroll center top;
}

答案 3 :(得分:0)

添加 background-size:cover ,或者您希望图片根据容器尺寸进行拉伸,但您的图片尺寸不同,因此您需要添加 background-size:100% 100%

请参阅下面的工作代码:

.banner {
  background: url(http://wallpaper-gallery.net/images/wallpaper-pc-background/wallpaper-pc-background-11.jpg);
  height: 400px;
  width: 100%;
  background-size: cover;
}

.banner h1 {
  color: #fff;
  font-size: 3em;
  padding-top: 2em;
  text-align: center;
}
<div class="banner">
<h1> I am the banner</h1>
</div>