JGallardo
JGallardo

Reputation: 11373

Fit image inside div height but center horizontal content while maintaining aspect ratio

Question

What should I edit to make the image be centered horizontally while fitting within the height of the containing <figure>?

The thumbnail will be 75px x 75px. Images uploaded may vary but will usually be approximately a 4:3 ratio, like 800px x 600px.


HTML

<figure>
    <img src="">
</figure>

Sass

figure {
    background-color: #777;
    display: inline-block;
    text-align: center;
    overflow: hidden;
    height: 75px;
    width: 75px;
    vertical-align: top;
    position: relative;
    z-index: 1;
    img {
        position: absolute;
        z-index: 5;
        height: 75px;
        width: auto !important;
        top: 50%;
        left: 50%;
        transform:translate(-50%, -50%);
    }
}

Upvotes: 0

Views: 38

Answers (1)

treyhakanson
treyhakanson

Reputation: 4911

Ideal Approach

The best way to do this and have good cross browser support is using a background-image instead of an actual image tag. Check out this codepen:

https://codepen.io/treyhakanson/pen/eGVVpr

Basically, using background-size: contain will cause the image to be bound by its largest dimension, while maintaining its aspect ratio, and background-position: center will center the image within its container.

Alternate Approach

If you cannot use background-image and must use img tags, check out the object-fit and object-position properties, which act similar to background-size and background-position, but for img and even video tags. It has good cross browser support, but not as good as the aforementioned method. examples of this have been added to the codepen link.

Upvotes: 2

Related Questions