CSS Image Size, How To Fill, But Not Stretch?
Answer :
You can use the css property object-fit.
.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
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.
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
heightproperty 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
heightandwidthattributes on theimageelement because they will be overridden by the style.
so it is enough to write something like this.<img class="cover" src="url to img ..." />
Comments
Post a Comment