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


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


当前回答

以下内容非常适合我:

img{
   height: 99999px;
   object-fit:contain;
   max-height: 100%;
   max-width: 100%;    
   display: block;
   margin: auto auto;
}

其他回答

将图像所需的高度和宽度提供给包含<img>标记的div。不要忘记在正确的样式标记中给出高度/宽度。

在<img>标记中,将最大高度和最大宽度设置为100%。

<div style="height:750px; width:700px;">
    <img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>

正确后,可以在适当的类中添加详细信息。

正如我在2014年Codepen示例中所看到的,我已经制定了一个解决方案,可以在尽可能少的javascript的帮助下处理任何未知的宽度/高度(纵横比)组合,以在容器的纵横比高于/低于图像的纵横比时更改图像居中的CSS:

尝试通过拖动右下角来调整容器大小:

//检测当前图像的窗口宽度是否过窄//并且适合于100%的高度而不是100%的宽度。const photo=文档.images[0]const onPhotoResize=新建ResizeObserver(条目=>window.requestAnimationFrame(checkRatio))onPhotoResize观察(photo.parentNode)函数checkRatio(){const photoParent=photo.parentNode,imageAspectRatio=照片客户端宽度/照片客户端高度,parentAspectRatio=photoParent.clientWidth/photoPrent.clientHeightphoto.classList[imageAspectRatio>parentAspectRatio?'add':'remove']('max')}.box格式{宽度:20%;高度:60%;边距:自动;位置:绝对;顶部:0;左:0;右:0;底部:0;调整大小:两者;溢出:隐藏;边框:5px纯红色;} .box>img{位置:绝对;顶部:50%;左:50%;宽度:100%;转换:转换(-50%,-50%);}.box>img.max{width:auto;height:100%;}<div class='box'><img src=“https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg"></div>

检查我的答案,使图像响应-最简单的方法-

img{
    width: 100%;
    max-width: 800px;
}

查看我的解决方案:http://codepen.io/petethepig/pen/dvFsA

它是用纯CSS编写的,没有任何JavaScript代码。它可以处理任何大小和方向的图像。

给定这样的HTML:

<div class="image">
  <div class="trick"></div>
  <img src="http://placekitten.com/415/200"/>
</div>

CSS代码将是:

.image {
  font-size: 0;
  text-align: center;
  width: 200px;  /* Container's dimensions */
  height: 150px;
}
img {
  display: inline-block;
  vertical-align: middle;
  max-height: 100%;
  max-width: 100%;
}
.trick {
  display: inline-block;
  vertical-align: middle;
  height: 150px;
}
<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>