Search code examples
cssimagecentering

Is it possible to center an image inside a wrapper with an overflow hidden?


I need my thumbnail to fill in the space of the container which is 100x100px. But I have some landscape images that I would like to have centered inside so they get cropped of left and right side. Is it possible to achieve this without using a background image.

Here is what I have so far:

HTML

<div class="outer">
    <div class="thumbnail">
        <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" alt="" />
    </div>
</div>

CSS

.outer {
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid grey
}

.thumbnail {
  overflow: hidden
}

img {
  width: auto;
  height: 100px;
}

http://codepen.io/ingvi/pen/JYjBNP?editors=110


Solution

  • If you don't mind about IE support, you can use object-fit: cover; property.

    css:

    .outer {
        margin: 0 auto;
        width: 100px;
        height: 100px;
        padding: 5px;
        border: 1px solid grey;
    }
    .thumbnail {
        overflow: hidden;
    }
    img {
        width: 100%;
        height: 100px;
        object-fit: cover;
    }
    

    html:

    <div class="outer">
            <div class="thumbnail">
                    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" alt="" />
            </div>
    </div>
    

    demo: https://jsfiddle.net/d0wvvdf8/1/