23tux 23tux - 5 months ago 24
CSS Question

Display img tag like background-size: contain

Is it possible to get a similar effect like

background-size: contain
with an
img
tag?

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
img
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
background-size
) 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



CSS:

.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.


EDIT:



  • This should work with CSS only, no JS.

  • Support for all modern browsers, including IE 10



Answer

Try to add this css:

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