Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Auto-Resize image through a hierarchy of elements to top element that specifies height

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading