最大高度为100%的父项溢出父项 [英] Child with max-height: 100% overflows parent

查看:107
本文介绍了最大高度为100%的父项溢出父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要了解对我而言是意外的行为:



我有一个容器内的max-height为100%的元素,使用max-height,但是意外的是,子进程溢出父进程:



测试用例: http://jsfiddle.net/bq4Wu/16/

  .container {
background : 蓝色;
padding:10px;
max-height:200px;
max-width:200px;
}

img {
display:block;
max-height:100%;
max-width:100%;
}

这是固定的,但是如果父级给定一个明确的高度: / p>

测试用例: http://jsfiddle.net/bq4Wu/17/

  .container {
height:200px;
}

有没有人知道为什么孩子不会尊重父母的最大高度在第一个例子? c $ c> max-height 当你为 max-height 对于子级,它是父级实际高度的百分比,而不是父级的 max-height 很奇怪。这同样适用于 max-width



因此,当您不在父级上指定显式高度时,子级的 max -height 以计算,因此 max-height 计算为 none 孩子要尽可能高。现在唯一的其他约束是它的父对象的 max-width ,并且由于图像本身比它的宽度更高,它会向下溢出容器的高度,



当您 指定父级的显式高度时,孩子知道它必须是该显式高度的至多100%。这允许它被约束到父级的高度(同时仍然保持其高宽比)。


I'm trying to understand what appears to be unexpected behaviour to me:

I have an element with a max-height of 100% inside a container that also uses a max-height but, unexpectedly, the child overflows the parent:

Test case: http://jsfiddle.net/bq4Wu/16/

.container {  
    background: blue; 
    padding: 10px; 
    max-height: 200px; 
    max-width: 200px; 
}

img { 
    display: block;
    max-height: 100%; 
    max-width: 100%; 
}

This is fixed, however, if the parent is given an explicit height:

Test case: http://jsfiddle.net/bq4Wu/17/

.container {  
    height: 200px;
}

Does anyone know why the child would not honour the max-height of its parent in the first example? Why is an explicit height required?

解决方案

When you specify a percentage for max-height on a child, it is a percentage of the parent's actual height, not the parent's max-height, oddly enough. The same applies to max-width.

So, when you don't specify an explicit height on the parent, then there's no base height for the child's max-height to be calculated from, so max-height computes to none, allowing the child to be as tall as possible. The only other constraint acting on the child now is the max-width of its parent, and since the image itself is taller than it is wide, it overflows the container's height downwards, in order to maintain its aspect ratio while still being as large as possible overall.

When you do specify an explicit height for the parent, then the child knows it has to be at most 100% of that explicit height. That allows it to be constrained to the parent's height (while still maintaining its aspect ratio).

这篇关于最大高度为100%的父项溢出父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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