Img的最大高度不尊重父母的尺寸 [英] Img's max-height not respecting parent's dimensions

查看:100
本文介绍了Img的最大高度不尊重父母的尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在液体 div 中有一个 img 元素。 img的 max-height 设置为100%。所以,如果图片比div高,它应该和div一样高。



.png文件的原始大小是200x200。在我的浏览器中,div显示为284x123。因此,img应该呈现为123x123,以保持其纵横比。

然而,img打破了div的边界,仍然显示为200x200。
我似乎无法弄清楚为什么会发生这种情况。



这发生在Chrome上,但不是Firefox上(我上次尝试过)。

p>

您可以查看当前状态此处 http://paginas.fe.up.pt/~ei07171/test/ )。
如果您将鼠标悬停在图片的左侧一侧,您会看到一个灰色箭头,即我正在讨论的.png。



编辑:我创建了一个单独的jsfiddle( http://jsfiddle.net/dcastro/3Ygwp/1/ ),其中img的最大高度似乎工作正常..我找不到什么在我的项目导致它不工作。

解决方案

我想通了。对于一个元素的最大高度的工作,其父母之一必须有一个高度属性定义(显然在一个固定的单位,如px,不是百分比)。



w3c规格


百分比是根据
生成框的包含区块的高度进行计算的。如果包含
块的高度没有明确指定(即它取决于内容
高度),并且该元素没有被绝对定位,则百分比
被视为'0' ('min-height')或'none'(对于
'max-height')。


由于没有我的img的父母有一个固定的高度定义,我不得不将我的img限制为max-width。



编辑:另外,它似乎webkit的规格太过于字面: https://stackoverflow.com/a/3808701/857807



我使用了该线程中提供的解决方法,并使用 position:absolute;最大高度:100%;顶部:0


I have an img element inside a liquid div. That img has its max-height set to 100%. So, if the image is taller than the div, it should be rendered as tall as the div.

The original size of the .png file is 200x200. In my browser, the div shows as 284x123. Therefore, the img should be rendered at 123x123, to keep its aspect ratio.

However, the img is breaking the div's bounds and still shows as 200x200. I can't seem to figure why this is happening.

This is happening on Chrome, but not on Firefox (last time I tried).

You can see the current state here (http://paginas.fe.up.pt/~ei07171/test/). If you hover over the left side of the picture, you'll see a grey arrow, the .png that i'm talking about. The arrow on the right side is a SVG file and works correctly.

Edit: I've created a separate jsfiddle (http://jsfiddle.net/dcastro/3Ygwp/1/), where the img's max-height seems to work correctly.. I can't find what on my project is causing it not to work.

解决方案

I figured it out. For an element's max-height to work, one of its parents must have a height attribute defined (apparently in a fixed unit, like px, not in percentage).

From the w3c specs:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').

Since none of my img's parent have a fixed height defined, I had to limit my img to max-width instead.

Edit: Also, it seems webkit takes the specs a little too literally: https://stackoverflow.com/a/3808701/857807

I used the workaround presented in that thread, and used position: absolute; max-height: 100%; top: 0.

这篇关于Img的最大高度不尊重父母的尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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