CSS 设置 divs 背景图像以适合其大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15313181/
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-29 21:58:04  来源:igfitidea点击:

Setting a divs background image to fit its size?

imagecss

提问by kfirba

I have a <div>with a background Image.

我有一个<div>背景图片。

The <div>size may change over the time.

<div>尺寸可在该时间而改变。

Is it possible setting the Divs Background image to fit the <div>size?

是否可以设置 Divs 背景图像以适应<div>大小?

Lets say I have a div which is 400x400and an Image which is 1000x1000, is it possible to shrink the image to 400x400and therefore fit the <div>size?

假设我有一个 div400x400和一个 Image 1000x1000,是否可以将图像缩小到400x400适合<div>大小?

回答by dsgriffin

If you'd like to use CSS3, you can do it pretty simply using background-size, like so:

如果你想使用 CSS3,你可以很简单地使用background-size,像这样:

background-size: 100%;

It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.

所有主流浏览器(包括 IE9+)都支持它。如果您想让它在 IE8 和更早版本中运行,请查看此问题的答案。

回答by kfirba

Use background-sizefor that purpose:

background-size为此目的使用:

background-size: 100% 100%;

More on:

更多关于:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

http://www.w3schools.com/cssref/css3_pr_background-size.asp

回答by MarcinJuraszek

Use background-sizeproperty to achieve that. You should choose between cover, containand 100%- depending on what exactly you'd like to get.

使用background-size财产来实现这一点。您应该在cover,contain100%-之间进行选择,具体取决于您想要获得的内容。

回答by Prajwal

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;

回答by Haresh Shyara

You could use the CSS3 background-size property for this.

您可以为此使用 CSS3 background-size 属性。

.header .logo {
background-size: 100%;
}

回答by Sankalp Singha

Use this as it can also act as responsive. :

使用它,因为它也可以作为响应。:

background-size: cover;

回答by miguel.gazela

Set your css to this

将你的 css 设置为这个

img {
    max-width:100%,
    max-height100%
}

回答by chiliNUT

Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size

想为IE8及以下(我认为低至IE5.5)添加解决方案,无法使用 background-size

div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}