如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?
示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。
如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?
示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。
当前回答
我刚刚发布了一个jQuery插件,它可以满足您的需要,提供了很多选项:
https://github.com/GestiXi/image-scale
用法:
HTML
<div class="image-container">
<img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg">
</div>
JavaScript
$(function() {
$("img.scale").imageScale();
});
其他回答
您必须告诉浏览器您放置它的高度:
.example {
height: 220px; /* DEFINE HEIGHT */
background: url('../img/example.png');
background-size: 100% 100%;
background-repeat: no-repeat;
}
一个简单的解决方案是使用Flexbox。将容器的CSS定义为:
.container{
display: flex;
justify-content: center;
align-items: center;
align-content: center;
overflow: hidden;
/* Any custom height */
}
将包含的图像宽度调整为100%,您将在容器中获得一个保持尺寸的居中图像。
正如我在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>
查看我的解决方案: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;
}
正如这里所回答的,你也可以使用vh单位而不是最大高度:如果它在你的浏览器(如Chrome)上不起作用,100%:
img {
max-height: 75vh;
}