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
- Looks good
- Should be centered vertically
- 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
2
Answers
Try to add this css:
You can do it like this by setting
position: relative
to the.product
andposition: absolute
with other formatting to the.product img
. Please check the fiddle below.