仅限CSS的max-height和max-width [英] max-height AND max-width with CSS only

查看:101
本文介绍了仅限CSS的max-height和max-width的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的第一篇文章。

First post for me here.

我正在使用div来以相同的比例(180wx170h)全部裁剪缩略图。在处理人像和风景图像时我陷入困境。如果使用的是适合人像风格的图片,则可以使用此图片:

I'm using a div to crop thumbnail images all in the same proportions (180wx170h). I'm getting stuck when dealing with portrait as well as landscape images. If am using this which is fine for portrait style images:

.crop img {max-height:170px; width:auto} 

..适用于风景图像:

.. and is fine for landscape style images:

.crop img {max-width:180px; height: auto;} is fine for landscape style images.  

所以我基本上想修剪侧面(如果横向)和顶部/底部(肖像)。有点像优先级的最大高度和最大宽度。

So I basically want to crop the sides if landscape and top/bottom if portrait. Kind of like a prioritized max-height and max-width.

我知道用PHP可以轻松做到这一点,但我真的只知道CSS,因此这是我的首选。

I know this could be done easily with PHP but I really only know CSS so that would be my first preference.

我需要保持图像的长宽比。

I need to maintain the aspect ratio of the image.

推荐答案

编辑2019:

如果要保留< img> 标签,请查看 object-fit css属性,在浏览器中对它的支持非常好。

If you want to keep <img> tags, please look into object-fit css property, support of it across browsers is quite good.

如果要保持宽高比不变,请尝试< a href = https://css-tricks.com/aspect-ratio-boxes/ rel = noreferrer> padding-hack 。

And if you want to keep aspect ratio on width change, try padding-hack.

据我了解,您有180x170像素的块,并且您想用图像完全填充它们。尝试将图像移到背景并使用 background-size:cover

As I understand you have blocks 180x170 px and you want to fill them completely with images. Try to move images to background and use background-size:cover.

演示 http://jsfiddle.net/heuku/ 1 /

<div style="background-image:url(http://placekitten.com/100/200)"></div>
<div style="background-image:url(http://placekitten.com/200/100)"></div>
<div style="background-image:url(http://placekitten.com/200/200)"></div>

div {
  width:180px;
  height:170px;
  background-repeat:no-repeat;
  background-size:cover;
}

请注意,此解决方案在IE8及更低版本中不起作用。

Note that this solution not working in IE8 and below.

这篇关于仅限CSS的max-height和max-width的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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