我还没有找到任何好的 CSS 代码来解决我的问题,并且适用于所有主流浏览器。
也就是说,每当我在父 div 中使用 max-height: 90%
并在子 img 中设置 max-height: 100%
时,safari 会自动执行此操作。然而,Mozilla 没有。
是否有任何跨浏览器解决方案来确保 img 不会扩展超过父 div 的高度。但是父div可以调整到 child 的高度,并限制在自己的max-height
?
我也接受 jQuery,但在答案中更喜欢 CSS。
当谈到宽度时,在父 div 中始终为 width: 60%
,在子 img 中为 max-width: 100%
。
代码
.fullScaleContent{
position: fixed;
width: 60%;
max-height: 90%;
height: auto;
margin: 2% auto;
-moz-box-sizing: border-box;
box-sizing: border-box;
left: 50%;
top: 50%;
transform: translate(-50%, -55%);
-webkit-transform: translate(-50%, -55%);
-ms-transform: translate (-50%, -55%);
}
.fullScaleContent img{
width:auto;
height:auto;
max-width: 100%;
max-height: 100%;
}
图片示例:第一张图片是 safari 中的高度限制,第二张是 Firefox 中的。我需要两者都类似于 safari。 PS:黑色边框是div的实际边框
宽度有限 - 两者都可以正常工作 - 高度根据 img 调整,最大宽度为 60%
最佳答案
如果您使用 position
,请在您的图像上使用它,以便它在流程中。
在整页中查看代码段并调整其大小。
片段
*,
*:before,
*:after {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
position: relative;
}
.fullScaleContent {
position: fixed;
width: 60%;
max-height: 90%;
height: auto;
margin: 2% auto;
left: 50%;
top: 50%;
transform: translate(-50%, -55%);
-webkit-transform: translate(-50%, -55%);
-ms-transform: translate (-50%, -55%);
}
.fullScaleContent img {
position: relative;
object-fit: contain;
min-width: 128px;
max-width: 100%;
height: auto;
}
<figure class="fullScaleContent">
<img src="https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png">
</figure>
关于jquery - 根据子图片高度改变父div高度,不超过父div max-width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515671/