I know that I can auto-resize an image by making it max-width:100%, max-height:100% when the immediate parent specifies a height. This is shown in Example 2. But I need to auto-resize when it is nested in a hierarchy of elements, where some ancestor specifies a height. In Example 1, because it’s not immediately under a height-specifying ancestor, the height:45px is not observed. Any quick solutions?
img {
max-height: 100%;
max-width: 100%;
}
.container1 {
height: 45px;
}
.container2 {
height: 45px;
}
<div class="container1">
<div class="header">
<a href='#'>
<img src='https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg' />
</a>
</div>
</div>
<br/><br/><br/><br/>
<div class="container2">
<img src="https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg" />
</div>
>Solution :
Set the intermediate elements to 100% height. This prevents them growing (and overflowing their container) to accommodate their large descendant image.
.container1 {
height: 45px;
}
.container1 .header, .container1 .header>a {
height: 100%;
}
.container2 {
height: 45px;
}
img {
height: 100%;
max-width: 100%;
}
<div class="container1">
<div class="header">
<a href='#'>
<img src='https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg' />
</a>
</div>
</div>
<br/><br/><br/><br/>
<div class="container2">
<img src="https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg" />
</div>