我在试着理解对我来说似乎出乎意料的行为:

我在一个容器中有一个max-height为100%的元素,该容器也使用了max-height,但出乎意料的是,子元素溢出了父元素:

.container { 背景:蓝色; 填充:10 px; max-height: 200 px; max-width: 200 px; } img { 显示:块; max-height: 100%; max-width: 100%; } < div class = "容器" > <img src="http://placekitten.com/400/500" /> < / div >

但是,如果父节点被指定了显式的高度,这个值是固定的:

.container { 背景:蓝色; 填充:10 px; max-height: 200 px; max-width: 200 px; 身高:200 px; } img { 显示:块; max-height: 100%; max-width: 100%; } < div class = "容器" > <img src="http://placekitten.com/400/500" /> < / div >

有人知道为什么在第一个例子中子节点不尊重父节点的max-height吗?为什么需要显式高度?


当前回答

一个很好的解决方案是在父对象上不使用height,只在带有View Port的子对象上使用它:

例如:https://jsfiddle.net/voan3v13/1/

body, html {
  width: 100%;
  height: 100%;
}
.parent {
  width: 400px;
  background: green;
}

.child {
  max-height: 40vh;
  background: blue;
  overflow-y: scroll;
}

其他回答

一个很好的解决方案是在父对象上不使用height,只在带有View Port的子对象上使用它:

例如:https://jsfiddle.net/voan3v13/1/

body, html {
  width: 100%;
  height: 100%;
}
.parent {
  width: 400px;
  background: green;
}

.child {
  max-height: 40vh;
  background: blue;
  overflow-y: scroll;
}

我在这里找到了一个解决方案: http://www.sitepoint.com/maintain-image-aspect-ratios-responsive-web-design/

这个技巧是可行的,因为它存在元素的WIDTH和PADDING-BOTTOM之间的关系。所以:

家长:

container {
  height: 0;
  padding-bottom: 66%; /* for a 4:3 container size */
  }

子(删除所有与width相关的CSS,即width:100%):

img {
  max-height: 100%;
  max-width: 100%;
  position: absolute;     
  display:block;
  margin:0 auto; /* center */
  left:0;        /* center */
  right:0;       /* center */
  }

这里是一个解决最近打开的问题,标记为这个问题的副本。<img>标签超过了父标签<div>的max-height。

破碎:小提琴

工作:小提琴

在这种情况下,向2个parent <div>标记添加display:flex就是答案

也许其他人可以解释你的问题背后的原因,但你可以通过指定容器的高度,然后将图像的高度设置为100%来解决这个问题。重要的是,图像的宽度出现在高度之前。

<html>
    <head>
        <style>
            .container {  
                background: blue; 
                padding: 10px;
                height: 100%;
                max-height: 200px; 
                max-width: 300px; 
            }

            .container img {
                width: 100%;
                height: 100%
            }
        </style>
    </head>
    <body>
        <div class="container">
            <img src="http://placekitten.com/400/500" />
        </div>
    </body>
</html>

容器通常已经很好地包装了它们的内容。反之往往就不一样了:孩子们不能很好地满足他们的祖先。因此,在最里面的元素上设置宽度/高度值,而不是在最外面的元素上,并让外面的元素包装它们的内容。

.container {
    background: blue;
    padding: 10px;
}

img {
    display: block;
    max-height: 200px;
    max-width: 200px;
}