Html CSS自动调整背景图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20830906/
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
CSS autosize background image?
提问by Alien13
This is probable one of the most basic questions on this website, hence I expect some quick answers. When I try to set a background image for my website I edit the image in paint and I constantly have to edit the image pixel for pixel in order to make the image cover up every single area of the website. Is there any standards or html codings that can automatically set resize the image to the exact size of the website?
这可能是本网站上最基本的问题之一,因此我希望得到一些快速答案。当我尝试为我的网站设置背景图像时,我会在 Paint 中编辑图像,并且我必须不断地逐个编辑图像像素,以使图像覆盖网站的每个区域。是否有任何标准或 html 编码可以自动将图像大小调整为网站的确切大小?
回答by Adonis K. Kakoulidis
You need to do something like this:
你需要做这样的事情:
/*************************************************************************************
by forcing `height: 100%` in the html and body tag will make sure there are no white areas in vicinity (this is optional though, use it only if you need it)
*************************************************************************************/
html,
body{
height: 100%;
}
/*************************************************************************************
by using `background-size: cover;`, you will make sure the image will cover everything
*************************************************************************************/
body{
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
background-image: url("your_image.jpg");
}
Also, consider using -moz-
, and -webit-
prefixes to make sure it works in older browser versions of webkit and gecko based browsers.
此外,请考虑使用-moz-
, 和-webit-
前缀以确保它适用于基于 webkit 和 gecko 的旧浏览器版本。
回答by Wilbert
In your CSS stylesheet you can use the following code (where images/bg.jpg is the path for your background image)
在您的 CSS 样式表中,您可以使用以下代码(其中 images/bg.jpg 是您的背景图片的路径)
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in: Safari 3+, Chrome, IE 9+, Opera 10+, Firefox 3.6+
适用于:Safari 3+、Chrome、IE 9+、Opera 10+、Firefox 3.6+
回答by vigonotion
Are you familiar with css? Add the background as image:
你熟悉css吗?将背景添加为图像:
<img src="yoursource.png" class="yourclass" />
and use this css snippet:
并使用此 css 片段:
.yourclass {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: -100; /* puts image into the background */
}
回答by jmore009
I'm assuming you're setting the background image on the body
but if not you should be. use background-size: cover;
which will stretch the image to fit
我假设您正在设置背景图像,body
但如果不是,您应该这样做。使用background-size: cover;
这将拉伸图像以适合