使用CSS限制响应图像的高度 [英] Limit the height of a responsive image with css

查看:162
本文介绍了使用CSS限制响应图像的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的最终目标是拥有一个流畅的< img> ,它不会仅使用css扩展到父/祖父母元素的显式设置高度。

My end goal is to have a fluid <img> that won't expand past an explicitly set height of a parent/grandparent element using only css.

当前,我正在使用普通(最大宽度:100;高度:自动; )流体进行此操作图像和javascript,方法是从img标签读取height / width属性,计算宽高比,在所需的高度限制下计算图像的正确宽度,并将该宽度作为 max-width 在图像的容器元素上。相当简单,但是我很希望不用javascript就可以做到。

Currently I'm doing this with a normal (max-width:100; height:auto;) fluid image and javascript by reading the height/width attributes from the img tag, calculating the aspect ratio, calculating the correct width of the image at the desired height restriction, and applying that width as a max-width on the image's container element. Pretty simple, but I'd love to be able to do it without javascript.

高度:100%; width:auto; 不能与它的横向相同,并且我已经尝试使用Unc Dave的ol'填充框和该功能的绝对定位,但是需要事先知道图像的长宽比因此无法应用于比例不同的图像。因此,最终要求是css必须与比例无关。

height:100%; width:auto; doesn't work the same as its transverse, and I've made some attempts with Unc Dave's ol' padded box and absolute positioning that function but require knowing the aspect ratio of the image beforehand and therefore cannot be applied across images that have different proportions. So the final requirement is the css must be proportion agnostic.

我知道,我知道,这个问题的答案可能在独角兽农场旁边,但我想我还是把它扔在那里。

I know, I know, the answer to this question is probably sitting next to the unicorn farm, but I thought I'd throw it out there anyways.

推荐答案

诀窍是将 max-height:100%; 最大宽度:100%; .container img 。 CSS示例:

The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

.container {
  width: 300px;
  border: dashed blue 1px;
}

.container img {
  max-height: 100%;
  max-width: 100%;
}

这样,您可以更改 .container 任意方式(例如200px或10%),图片将不会大于其自然尺寸。 (如果您不想依赖图像的自然尺寸,则可以指定像素而不是100%。)

In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

这里是整个小提琴: http://jsfiddle.net/KatieK/Su28P/1/

这篇关于使用CSS限制响应图像的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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