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

查看:15
本文介绍了使用 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.

目前我正在使用普通的 (max-width:100; height:auto;) 流体图像和 javascript,通过从 img 标签读取高度/宽度属性,计算方面比率,在所需的高度限制下计算图像的正确宽度,并将该宽度作为 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%;max-width: 100%;code> 到 .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天全站免登陆