[英]max-height image inside of grid with min-height should respect the grid's size rather than extending it
我有一个 3 列 2 行的布局,使用min-height
为90vh
的网格。
左右两列包含一个图像,该图像应该朝向中心列对齐,并且应该垂直对齐(如果它小于其单元格,则不应放大)。 但是,图像不应超过其单元格的最大宽度( max-width: 100%
),并且不应超过其单元格的最大高度( max-height: 100%
); 如果是这样,它应该被缩小。
第二行包含一个标题。 此标题应锚定在网格底部,但不能假定固定高度。
问题是当网格使用min-height
而不是height
时,图像使用max-height
时,不会发生图像的缩小。 相反,图像会强制网格单元垂直增长。
.container {
display: grid;
grid-template-columns: 1fr 100px 1fr;
grid-template-rows: 1fr auto;
min-height: 90vh;
}
/* these are applied to img elements directly inside the grid */
.left, .right {
max-width: 100%;
max-height: 100%;
align-self: center;
}
.left {
justify-self: right;
}
.right {
justify-self: left;
}
<div class="container">
<img class="left" src="https://i.imgur.com/2byCwGq.jpg"/>
<div class="center">center column</div>
<img class="right" src="https://i.imgur.com/tzPAOIo.jpg"/>
<div>caption left</div>
<div>caption center</div>
<div>caption right</div>
</div>
注意:我使用min-height
而不是height
因为中间列可能超过90vh
,如果我使用height
,网格中溢出的内容会与网格本身重叠(这是不可取的)。
下面是一个演示页面。 当视口高度降低时,在某些时候,两个图像中较高的一个将足够大,以至于其网格单元格高度增加并且总网格高度将超过 90vh。
<html> <head> <style type="text/css">.container { display: grid; grid-template-columns: 1fr 100px 1fr; grid-template-rows: 1fr auto; min-height: 90vh; background-color: #077; }.left, .right { max-width: 100%; max-height: 100%; align-self: center; }.left { justify-self: right; }.right { justify-self: left; }.center { background-color: #770; } </style> </head> <body> <div class="container"> <img class="left" src="https://i.imgur.com/2byCwGq.jpg"/> <div class="center">center column</div> <img class="right" src="https://i.imgur.com/tzPAOIo.jpg"/> <div style="background-color: #700">caption left</div> <div style="background-color: #700">caption center</div> <div style="background-color: #700">caption right</div> </div> <hr/> <p>after container</p> </body> </html>
我不确定 stackoverflow 内联预览是否正确处理视口单元。 如果是这样,您可以立即看到图像没有缩小,因此网格的高度肯定超过90vh
。 当网格有height
而不是min-height
时,它可以工作,但是一旦网格容器太小,网格容器之后的内容可能会与网格容器重叠。
我尝试了一堆不同的宽度/高度组合,对齐自我等,但没有运气。
如何使 img 的max-height: 100%
尊重其父网格的单元格高度?
您也可以将等于90vh
的max-heigh
height t 属性分配给.left
和.right
。
您还可以使用object-fit
属性来包含图像。
.left, .right {
max-width: 100%;
max-height: 90vh;
align-self: center;
object-fit: contain
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.