保持最小/最大高度/宽度的纵横比? [英] Maintaining aspect ratio with min/max height/width?

查看:36
本文介绍了保持最小/最大高度/宽度的纵横比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个图库,用户可以在其中上传图片.

我希望图像位于保持其高度的 div 中,图像的高度不应大于 500 像素.宽度应该是自动的以保持纵横比.

HTML:

我已经尝试过这个 CSS:

#gallery{高度:500px;图片{最大高度:500px;最大宽度:100%;}}

以上效果很好,图库的高度始终为 500 像素,图像的高度永远不会超过 500 像素.我遇到了小图像的问题,如果用户上传了一个非常小的图像,我希望它放大"到至少 200 像素.我知道这可以通过在图像上设置 min-height 来实现,问题是,如果图像的高度小于 200 像素,但比方说 2000 像素宽,图像会被放大到高度为 200 像素,但是纵横比被搞砸了,因为图像比图像父 div 宽.

我怎样才能有最小高度但保持纵横比?

解决方案

您正在寻找的属性是 object-fit.这是 Opera 的创新之一,您可以在他们的 2011 年关于对象的开发文章中阅读更多相关信息-合身(是的,已经有这么久了).几年前,我无法向您推荐它,但是 caniuse 表明其他所有人都开始追赶:

  • Opera 10.6-12.1(-o- 前缀)
  • Chrome 31+
  • Opera 19+
  • Safari 7.1+
  • iOS 8+
  • Android 4.4+

http://caniuse.com/#search=object-fit

#gallery img {-o-object-fit:包含;适合对象:包含;}

使用 contain 值将强制图像无论如何保持其纵横比.

或者,您可能想改用它:

#gallery img {-o-object-fit:覆盖;适合对象:覆盖;溢出:隐藏;}

http://sassmeister.com/gist/9b130efdae95bfa4338e

I have a gallery on my site where users can upload images.

I would like the images to sit in a div that maintains its height, the images should be no larger than 500px in height. The width should be automatic to maintain aspect ratio.

HTML:

<div id="gallery">
    <img src="uploads/my-dynamic-img.jpg">
</div>

I've tried this CSS:

#gallery{
    height: 500px;

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

The above works well, the gallery is always 500px high and images never exceed 500px in height. I run into problems though with smaller images, if a user uploads a really small image, I would like it 'blown up' to a minimum of 200px. I know this can be achieved by setting a min-height on the image, the problem with this is, if the image is less than 200px in height but say, 2000px wide, the image gets blown up to 200px in height, but then the aspect ratio is screwed, as the image is wider than the images parent div.

How can I have a min height but retain aspect ratio?

解决方案

The property you're looking for is object-fit. This is one of Opera's innovations, you can read more about it in their 2011 dev article on object-fit (yep, it's been around that long). A few years ago, I wouldn't have been able to recommend it to you, but caniuse shows that everyone else is starting to catch up:

  • Opera 10.6-12.1 (-o- prefix)
  • Chrome 31+
  • Opera 19+
  • Safari 7.1+
  • iOS 8+
  • Android 4.4+

http://caniuse.com/#search=object-fit

#gallery img {
    -o-object-fit: contain;
    object-fit: contain;
}

Using a value of contain will force the image to maintain its aspect ratio no matter what.

Alternately, you might want to use this instead:

#gallery img {
    -o-object-fit: cover;
    object-fit: cover;
    overflow: hidden;
}

http://sassmeister.com/gist/9b130efdae95bfa4338e

这篇关于保持最小/最大高度/宽度的纵横比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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