如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?


示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。


当前回答

我以这种方式在超链接内水平和垂直居中并按比例缩放图像:

#link {
    border: 1px solid blue;
    display: table-cell;
    height: 100px;
    vertical-align: middle;
    width: 100px;
}
#link img {
    border: 1px solid red;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-height: 60px;
    max-width: 60px;
}

它在Internet Explorer、Firefox和Safari中进行了测试。

有关居中的更多信息,请参阅此处。

其他回答

<style type="text/css">
    #container{
        text-align: center;
        width: 100%;
        height: 200px; /* Set height */
        margin: 0px;
        padding: 0px;
        background-image: url('../assets/images/img.jpg');
        background-size: content; /* Scaling down large image to a div */
        background-repeat: no-repeat;
        background-position: center;
    }
</style>

<div id="container>
    <!-- Inside container -->
</div>

有两种方法可以使图像具有响应性。

当图像是背景图像时。#集装箱{宽度:300px;高度:300px;背景图像:url(https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);背景尺寸:封面;背景重复:无重复;背景位置:中心;}<div id=“container”><div>在这里运行但是应该使用img标记来放置图像,因为它在SEO方面比背景图像更好,因为您可以在img标记的alt中写入关键字。因此,您可以使图像具有响应性。当图像在img标记中时。#集装箱{最大宽度:400px;溢出:隐藏;}国际货币基金组织{宽度:100%;对象拟合:包含;}<div id=“container”><img src=“https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg“alt=”your_keyword“/><div>在这里运行

所有提供的答案,包括已接受的答案,都只能在假设div包装器大小固定的情况下工作。因此,无论div包装器的大小如何,这都是如何实现的,如果您开发响应页面,这非常有用:

在DIV选择器中编写以下声明:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

然后将这些声明放入IMG选择器中:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

非常重要:

对于DIV和IMG选择器,maxHeight的值必须相同。

当图像太小时,Thorn007的公认答案不起作用。

为了解决这个问题,我添加了一个比例因子。这样,它会使图像变大,并填充div容器。

例子:

<div style="width:400px; height:200px;">
  <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>

笔记:

对于WebKit,必须添加-WebKit transform:scale(4)-webkit转换原点:左上;在风格上。比例因子为4时,最大宽度=400/4=100,最大高度=200/4=50另一种解决方案是将最大宽度和最大高度设置为25%。这更简单。

此解决方案不会拉伸图像并填充整个容器,但会剪切部分图像。

HTML格式:

 <div><img src="/images/image.png"></div>

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}