CSS 使背景图像响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22556250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:07:40  来源:igfitidea点击:

Make background image responsive

cssresponsive-designbackground-image

提问by insanity

I want to make background image responsive both in width as well as in height so that i can run it in mobile.

我想让背景图像在宽度和高度上都具有响应性,以便我可以在移动设备上运行它。

I have used this

我用过这个

.your_background_class_name {
    width: 100%;
    height:auto;
    top: 0px;
    left: 0px;
    z-index: -1;
    position: absolute;

}

but it works in width only not in height. What changes should i do to make it work?

但它只适用于宽度而不适用于高度。我应该做哪些更改才能使其正常工作?

回答by newTag

html { 
  background: url(https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSvctt0I--skoKQVfuVt-i4Et6vQ5ve7lXPkLy9sTElCWLKh1Ps) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Know more about background-sizehere.

background-size在这里了解更多。

See demo

看演示

回答by Mykola Lys

The following code should do the trick:

以下代码应该可以解决问题:

class_name {
    background: url(image);
    background-size: 100% auto contain;
}

回答by AlphaX

This worked for me:

这对我有用:

#header {
background-image: url('http://www.fillmurray.com/g/1920/1080');
background-repeat:no-repeat;
background-size: 100%;
background-position:top left;
position: relative;
}

#header .container {
height: 893px;
position: relative;
}

#header .div1 {
position: absolute;
top: 20px;
}

#header .div2 {
position: absolute;
bottom: 20px;
right: 20px;
}
<div id="header">
<div class="container">
    <div class="div1">
        Top left content
    </div>
    <div class="div2">
        Bottom right content
    </div>
</div>