强制图像适合并保持宽高比 [英] Force an image to fit and keep aspect ratio

查看:95
本文介绍了强制图像适合并保持宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个图像来填充它的容器宽度的100%,并且我希望它有一个max-heigth属性设置,这一切都保持了纵横比,但是允许丢失图像的任何部分。 p>

  img {
最大高度:200px;
宽度:100%;
}

我知道类似的事情可以用 background -size 属性,但是我想将它作为内联< img> 标签。



任何想法,我怎么能实现这个使用CSS?或者javascript?

解决方案

您可以尝试CSS3 object-fit strong> 表格 $ b


CSS3 object-fit / object-position 指定对象(图像或视频)应该如何放置在
框内的方法。对象适合选项包括包含(根据方面
比例拟合),填充(伸展对象填充)和覆盖(溢出框
但保持比例),其中对象位置允许
被重新定位,如background-image。

://jsfiddle.net/k7h1xvr7/rel =noreferrer> JSFIDDLE DEMO



  .container {width:200px; / *任何尺寸* / height:200px; / *任意大小* /}。object-fit-cover {width:100%;身高:100%;物体贴合:封面; / * magic * /}  

< div class =容器> < img class =object-fit-coversrc =https://i.stack.imgur.com/UJ3pb.jpg>< / div>




I want an image to fill the 100% of its container's width, and I want it to have a max-heigth property set to it, all this keeping the aspect ratio but allowing to lose any part of the image.

img {
   max-height:200px;
   width:100%;
}

I know a similar thing can be done with background-size property but i want to make this to an inline <img> tag.

Any idea of how could i achieve this using CSS? or javascript?

解决方案

You can try CSS3 object-fit, and see browser support tables.

CSS3 object-fit/object-position Method of specifying how an object (image or video) should fit inside its box. object-fit options include "contain" (fit according to aspect ratio), "fill" (stretches object to fill) and "cover" (overflows box but maintains ratio), where object-position allows the object to be repositioned like background-image does.

JSFIDDLE DEMO

.container {
  width: 200px; /*any size*/
  height: 200px; /*any size*/
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}

<div class="container">
  <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg">
</div>


Related Info:

这篇关于强制图像适合并保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆