Html 使用 CSS,如何使图像跨越页面的整个宽度作为背景图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12082913/
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
With CSS, how do I make an image span the full width of the page as a background image?
提问by Doug Smith
Say, like in this example here: http://www.electrictoolbox.com/examples/wide-background-image.html
说,就像这里的这个例子:http: //www.electrictoolbox.com/examples/wide-background-image.html
When I do it, I end up getting white borders around the image no matter what I do. What am I doing wrong?
当我这样做时,无论我做什么,我最终都会在图像周围出现白色边框。我究竟做错了什么?
回答by sellmeadog
If you're hoping to use background-image: url(...);
, I don't think you can. However, if you want to play with layering, you can do something like this:
如果您希望使用background-image: url(...);
,我认为您不能。但是,如果你想玩分层,你可以这样做:
<img class="bg" src="..." />
And then some CSS:
然后是一些 CSS:
.bg
{
width: 100%;
z-index: 0;
}
You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%;
to apply to the whole page.
您现在可以通过使用 z-indexes 等在拉伸图像上方分层内容。一个快速说明,图像不能包含在任何其他元素中width: 100%;
以应用于整个页面。
Here's a quick demo if you can't rely on background-size
: http://jsfiddle.net/bB3Uc/
如果您不能依赖,这里有一个快速演示background-size
:http: //jsfiddle.net/bB3Uc/
回答by AliInvestor
Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.
理想情况下,背景图像总是使用 CSS 完成。所有其他图像都是用 html 完成的。这将跨越您网站的整个背景。
body {
background: url('../images/cat.ong');
background-size: cover;
background-position: center;
background-attachment: fixed;
}
回答by adeneo
You set the CSS to :
您将 CSS 设置为:
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
它使图像居中,但不缩放。
In newer browsers you can use the background-size
property and do:
在较新的浏览器中,您可以使用该background-size
属性并执行以下操作:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
除此之外,常规图像是一种方法,但它并不是真正的背景图像。
?
?