我试图了解对我来说似乎是出乎意料的行为:
我在容器内部有一个最大高度为100%的元素,该元素也使用了最大高度,但是,出乎意料的是,子元素溢出了父元素:
测试用例: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%;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果父级具有明确的高度,则这是固定的:
测试用例:http://jsfiddle.net/bq4Wu/17/
.container {
height: 200px;
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么孩子在第一个例子中不会尊重其父母的最大身高?为什么需要明确的高度?
Bol*_*ock 177
当您为max-height孩子指定百分比时,它是父母的实际身高的百分比,而不是父亲的百分比max-height,奇怪的是.这同样适用于max-width.
因此,当您没有在父级上指定显式高度时,则没有用于max-height计算子级的基本高度,因此max-height计算none,允许子级尽可能高.现在作用于孩子的唯一其他约束是max-width它的父,并且因为图像本身比它宽,所以它向上溢出容器的高度,以便保持其纵横比,同时仍然尽可能大.
当你做指定家长一个明确的高度,那么孩子知道它是在显式高度的至多100%.这允许它被约束到父亲的身高(同时仍然保持其纵横比).
Dan*_*iel 62
.container {
background: blue;
padding: 10px;
max-height: 200px;
max-width: 200px;
float: left;
margin-right: 20px;
}
.img1 {
display: block;
max-height: 100%;
max-width: 100%;
}
.img2 {
display: block;
max-height: inherit;
max-width: inherit;
}Run Code Online (Sandbox Code Playgroud)
<!-- example 1 -->
<div class="container">
<img class='img1' src="http://via.placeholder.com/350x450" />
</div>
<!-- example 2 -->
<div class="container">
<img class='img2' src="http://via.placeholder.com/350x450" />
</div>Run Code Online (Sandbox Code Playgroud)
我玩了一下.在firefox中的较大图像上,使用inherit属性值得到了很好的结果.这对你有帮助吗?
.container {
background: blue;
padding: 10px;
max-height: 100px;
max-width: 100px;
text-align:center;
}
img {
max-height: inherit;
max-width: inherit;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我在这里找到了解决方案:http : //www.sitepoint.com/maintain-image-aspect-ratios-sensitive-web-design/
之所以可行,是因为它存在于元素的宽度和填充底部之间的关系。所以:
父母:
container {
height: 0;
padding-bottom: 66%; /* for a 4:3 container size */
}
Run Code Online (Sandbox Code Playgroud)
子级(删除与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 */
}
Run Code Online (Sandbox Code Playgroud)
与 max-height: 100%/100% 不同,填充所有空间的另一种方法是将position: absolutetop/bottom/left/right 设置为 0。
换句话说,HTML 将如下所示:
<div class="flex-content">
<div class="scrollable-content-wrapper">
<div class="scrollable-content">
1, 2, 3
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
.flex-content {
flex-grow: 1;
position: relative;
width: 100%;
height: 100%;
}
.scrollable-content-wrapper {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
overflow: auto;
}
.scrollable-content {
}
Run Code Online (Sandbox Code Playgroud)
您可以在Codesandbox 中看到一个实时示例- CSS Flex/Grid 中的溢出
您可以使用属性object-fit
.cover {
object-fit: cover;
width: 150px;
height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
喜欢这里建议
Chris Mills 在 Dev.Opera中对该属性的完整解释
还有一个更好的 CSS-Tricks
它支持
我刚刚检查了 vivaldi 和 Chromium 也支持它(这并不奇怪)
目前 IE 不支持它,但是...谁在乎?此外,iOS 支持 object-fit,但不支持 object-position,但很快就会支持。