.div1 {
position: relative;
padding-bottom: 25%;
background: lightcoral;
}
.img-container {
position: absolute;
height: 100%;
background: green;
}
.img1 {
height: 100%;
opacity: 50%;
}
<div class="div1">
<div class="img-container">
<img src="https://placehold.co/600x300" alt="" class="img1">
</div>
</div>
Chrome result (expected result):
Firefox result (wrong result):
As you can see, in Firefox the width of the green div is just some random value, and not the width of its descendants (I fail to see any logic behind it).
Images must be able to have variable width, so this solution won't work for me (can't set fixed width on .img-container
).
What am I doing wrong?
This does appear to highlight an inconsistency between Edge/Chrome/Safari and Firefox.
If the grandparent has no explicit height set, the only height in this case being given by the padding-bottom, then FF seems to take the natural width of the image, not its width calculated in relation to height: 100%.
Giving div1 height of 25cqw (to be the same as the padding, padding being calculated in terms of widths not heights) plus box-sizing set at border-box to 'absorb' the padding, rectifies this, but of course may upset something else if there is other material within div1.
.div1 {
position: relative;
padding-bottom: 25%;
background: lightcoral;
height: 25cqw;
box-sizing: border-box;
}
.img-container {
position: absolute;
height: 100%;
background: green;
}
.img1 {
height: 100%;
opacity: 50%;
}
<div class="div1">
<div class="img-container">
<img src="https://placehold.co/600x300" alt="" class="img1">
</div>
</div>
So, this gives a workaround for the problem as set, but you need to look out for other dependencies in the real-life case.