23tux 23tux - 1 year ago 106
CSS Question

Display img tag like background-size: contain

Is it possible to get a similar effect like

background-size: contain
with an

I want to display product pictures inside a fixed width/height div container, that have various dimensions (square, portrait, landscape). The pictures should

  • Always display the whole image, nothing should be cropped

  • Be aligned horizontally and vertically centered

This is, what
background-size: contain
does. Unfortunately I have to use an
tag (vor various reasons, going from the framework I use to SEO stuff).

In this plnkr you can see the problems and how it should look like (using
) http://plnkr.co/edit/k9Nv4ELoZgYCaQfVuSDQ?p=preview

  1. Looks good

  2. Should be centered vertically

  3. Is cropped, but should display 100% of its height


.product {
background-color: green;
border: 1px solid blue;
width: 200px;
height: 200px;
overflow: hidden;
margin-bottom: 20px;

.product img {
width: 100%;

Note: Somehow I can't insert HTML tags, it displays the images not the
source code. Please have a look into the plnkr.


  • This should work with CSS only, no JS.

  • Support for all modern browsers, including IE 10

Answer Source

Try to add this css:

.product img {
  max-width: 200px;
  margin: 0 auto;
  display: block;
  position: relative;
  top: 50%;
  transform: translateY(-50%);