简体   繁体   中英

Fluid Image Contained in Fluid Container

I have an image wrapper with a maximum height and width constraint (in this example 300x200), and I'm trying to place a fluid image inside the container that respects those constraints.

The width of the image scales as expected, however the image's height always overflows beyond the parent div. What's the proper way to get this image to scale appropriately with CSS alone?

 .container { max-width: 500px; overflow: hidden; background-color: #eef; margin: 0 auto; } .figure-image-wrapper { max-width: 300px; max-height: 200px; margin: 0 auto; } .figure-image { max-width: 100%; height: auto; } .figure-caption { text-align: center; } 
 <div class="container"> <figure class="figure"> <div class="figure-image-wrapper"> <img src="//placehold.it/700x700" class="figure-image"/> </div> <figcaption class="figure-caption">This is my caption. It's expect to span beyond the width of the image. The image above should scale within a 300x200 .figure-image-wrapper</figcaption> </figure> </div> 

This should work for you:

.figure-image-wrapper {
    max-width: 300px;
    max-height: 200px;
    margin: 0 auto;
    text-align: center;
}

.figure-image {
    max-width: inherit;
    max-height: inherit;
}

DEMO

Ahah! The trick is to have only the max-height of the image inherit from the parent wrapper:

 .container { max-width: 500px; overflow: hidden; background-color: #eef; margin: 0 auto; } .figure-image-wrapper { max-width: 300px; max-height: 200px; margin: 0 auto; text-align: center; /* Added: Center the image */ } .figure-image { max-width: 100%; /* Removed: height: auto; */ max-height: inherit; /* Added */ } .figure-caption { text-align: center; } 
 <div class="container"> <figure class="figure"> <div class="figure-image-wrapper"> <img src="//placehold.it/700x700" class="figure-image"/> </div> <figcaption class="figure-caption">This is my caption. It's expect to span beyond the width of the image. The image above should scale within a 300x200 .figure-image-wrapper</figcaption> </figure> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM