Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

html - Img's max-height not respecting parent's dimensions

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...