Html 在 DIV 中展开图像

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

Expand image inside DIV

html

提问by Cornel

How can I expand an image to have the same height as the div after resizing? Or how can I fill the white space left by the image with a color?

调整大小后如何将图像扩展为与 div 相同的高度?或者如何用颜色填充图像留下的空白区域?

回答by Dave L

I think this will get you your desired result:

我认为这会让你得到你想要的结果:

<style>
    div {
    width:50px;
    height:100px;
    }

    div img {
    height:100%;
    }
</style>
<div>
    <img src='path/to/img.gif' />
</div>

The image will now fill to the container div's height and scale its width with its aspect ratio. This could cause the image to expand past the container div's intended width boundaries though so be careful.

图像现在将填充到容器 div 的高度并根据其纵横比缩放其宽度。这可能会导致图像扩展超过容器 div 的预期宽度边界,但要小心。

回答by vamin

There is a way to do this in CSS3:

在 CSS3 中有一种方法可以做到这一点:

div {background-image: url(path/to/image); background-size: 100%}

The background-size property is only supported in newer versions of Safari and Opera. For the other browsers, you can fill the whitespace left around the image with a color using the background-color property, like so:

background-size 属性仅在较新版本的 Safari 和 Opera 中受支持。对于其他浏览器,您可以使用 background-color 属性用颜色填充图像周围的空白,如下所示:

div {
  background-image: url(path/to/image);
  background-size: 100%;
  background-color: #000000;
  }

Or, in shorthand:

或者,简而言之:

div {background:#000000 url(path/to/image) no-repeat; background-size:100%}

Using this code will cause the image to stretch in CSS3 enabled browsers (newest Opera, Safari, and possibly Firefox). Older browsers and IE will have the whitespace around the image filled with the background color specified.

使用此代码将导致图像在支持 CSS3 的浏览器(最新的 Opera、Safari 和可能的 Firefox)中拉伸。较旧的浏览器和 IE 将使用指定的背景颜色填充图像周围的空白。

回答by rahul

Set a background color for the container div

为容器 div 设置背景颜色