简体   繁体   English

使背景图片适合 div

[英]Fit background image to div

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?有没有办法在不切断背景图像的情况下显示背景图像?

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;

JSFiddle example JSFiddle 示例

There also exists a filter for IE 5.5+ support , as well as vendor prefixes for some older browsers .还有一个过滤器用于 IE 5.5+ 支持,以及一些旧浏览器的供应商前缀

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

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">
background-position-x: center;
background-position-y: center;

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.为 div 制作具有固定宽度的背景图像(如果您愿意的话)可能非常困难,因此最好使用 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 并不复杂,只需确保以正确的方式设置父元素的样式,这样图像就有了可以进入的位置。

Chris克里斯

try any of the following,尝试以下任何一项,

background-size: contain;
background-size: cover;
background-size: 100%;

.container{
    background-size: 100%;
}

选择:

background-size: auto 100%;

you can also try this, set background size as cover and to get it look nicer also set background position center like so:你也可以试试这个,将背景大小设置为封面,为了让它看起来更好,还可以像这样设置背景位置中心:

background-size: cover;
background-position: center ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM