CSS Image size, how to fill, but not stretch?
You can use the css property object-fit
. ("sets how the content of a replaced element, such as an <img>
or <video>
, should be resized to fit its container.")
.cover {
object-fit: cover;
width: 50px;
height: 100px;
}
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
See example here
There's a polyfill for IE: https://github.com/anselmh/object-fit
Related: object-position
(specifies the alignment of an element's contents within its box.)
Enhancement on the accepted answer by @afonsoduarte.
in case you are using bootstrap
There are three differences:
Providing
width:100%
on the style.
This is helpful if you are using bootstrap and want the image to stretch all the available width.Specifying the
height
property is optional, You can remove/keep it as you need.cover { object-fit: cover; width: 100%; /*height: 300px; optional, you can remove it, but in my case it was good */ }
By the way, there is NO need to provide the
height
andwidth
attributes on theimage
element because they will be overridden by the style.
so it is enough to write something like this.<img class="cover" src="url to img ..." />
If you want to use the image as a CSS background, there is an elegant solution. Simply use cover
or contain
in the background-size
CSS3 property.
.container {
width: 150px;
height: 100px;
background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
}
<div class="container"></div>
While cover
will give you a scaled up image, contain
will give you a scaled down image. Both will preserve the pixel aspect ratio.
http://jsfiddle.net/uTHqs/ (using cover)
http://jsfiddle.net/HZ2FT/ (using contain)
This approach has the advantage of being friendly to Retina displays as per Thomas Fuchs' quick guide.
It's worth mentioning that browser support for both attributes excludes IE6-8.