Html 使背景图像适合 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8200204/
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
Fit background image to div
提问by Rajeev
I have a background image in the following div, but the image gets cut off:
我在以下 div 中有一个背景图像,但图像被截断了:
<div style='text-align:center;background-image: url(/media/img_1_bg.jpg);background-repeat:no-repeat;width:450px;height:900px;' id="mainpage" align="center">
Is there a way to show the background image without cutting it off?
有没有办法在不切断背景的情况下显示背景图像?
回答by grc
You can achieve this with the background-size
property, which is now supported by most browsers.
您可以使用该background-size
属性来实现这一点,现在大多数浏览器都支持该属性。
To scale the background image to fit inside the div:
要缩放背景图像以适合 div:
background-size: contain;
To scale the background image to cover the whole div:
要缩放背景图像以覆盖整个 div:
background-size: cover;
There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.
还有一个过滤器支持 IE 5.5+,以及一些旧浏览器的供应商前缀。
回答by Sertage
If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:
如果您需要的是具有与 div 相同尺寸的图像,我认为这是最优雅的解决方案:
background-size: 100% 100%;
If not, the answer by @grc is the most appropriated one.
如果没有,@grc 的答案是最合适的。
Source: http://www.w3schools.com/cssref/css3_pr_background-size.asp
来源:http: //www.w3schools.com/cssref/css3_pr_background-size.asp
回答by hojjat.mi
You can use this attributes:
您可以使用此属性:
background-size: contain;
background-repeat: no-repeat;
and you code is then like this:
然后你的代码是这样的:
<div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">
回答by Christian
you also use this:
你也用这个:
background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%;
I don't know your div-values, but let's assume you've got those.
我不知道你的 div 值,但让我们假设你有这些。
height: auto;
max-width: 600px;
Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.
同样,这些只是随机数。为 div 制作具有固定宽度的背景图像(如果您愿意)可能非常困难,因此最好使用 max-width。实际上,用背景图像填充 div 并不复杂,只需确保以正确的方式设置父元素的样式,这样图像就有了可以放入的位置。
Chris
克里斯