Here's the scenario: Can an image's max-height property be made to respect the fixed height of an ancestor element that is not its direct parent?
I am aware that max-height
requires a fixed height for calculation, so this query is distinct from those wondering why max-height does not function automatically.
I have a container (.rightbox
) with 100% height, positioned absolutely within a container of auto-defined height. This container adheres to the anticipated height.
Within this container, there is a child element set to a maximum height of 100%. This child also aligns with the expected height due to its parent's defined height (% + absolute positioning).
However, when an image is placed inside this container, it fails to conform to the specified max-height. I assumed that having an ancestor element with a calculable height would enable the image to adhere to the max-height limit.
The max-width property works as intended, leveraging the same ancestor for width calculations.
Even setting a pixel-based height on .rightbox
yields no results.
Interestingly, removing the intermediary div between .rightbox
and the img
causes the image to comply with the desired max-height.
*{
box-sizing:border-box;
margin:0;
padding:0;
}
.item{
width: 100%;
position:relative;
background:#0FF;
}
.rightbox::after{
content:"";
display:inline-block;
height:100%;
width:0;
vertical-align:middle;
}
.rightbox>div{
display:inline-block;
vertical-align:middle;
}
.rightbox{
position:absolute;
height:100%;
width:50%;
top:0;
right:0;
}
.rightbox>div,
.rightbox img{
max-height:100%;
max-width:100%;
}
.rightbox img{
opacity:0.7;
}
<div class="item">
<div>
<p>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
Some text to make this bigger.
</p>
</div>
<div class="rightbox">
<div>
<img src="http://via.placeholder.com/550x900" />
</div>
</div>
</div>