CSS Image size, how to fill, not stretch?
I have an image, and I want to set it a specific width and height (in pixels)
But If I set width and height using css ( width:150px; height:100px
), image will be stretched, and It may be ugly.
How to Fill images to a specific size using CSS, and not stretching it?
Example of fill and stretching image:
Original Image:
Stretched Image:
Filled Image:
Please note that in the Filled image example above: first, image is resized to 150x255 (maintained aspect ratio), and then, it cropped to 150x100.
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.
<div class="container"></div>
.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%;
}
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. http://cl.ly/0v2u190o110R
It's worth mentioning that browser support for both attributes excludes IE6-8. http://www.quirksmode.org/css/background.html
You can use the css property object-fit
.
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
.cover {
object-fit: cover;
width: 50px;
height: 100px;
}
See example here
There's a polyfill for IE: https://github.com/anselmh/object-fit
The only real way is to have a container around your image and use overflow:hidden
:
HTML
<div class="container"><img src="ckk.jpg" /></div>
CSS
.container {
width: 300px;
height: 200px;
display: block;
position: relative;
overflow: hidden;
}
.container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
It's a pain in CSS to do what you want and center the image, there is a quick fix in jquery such as:
var conHeight = $(".container").height();
var imgHeight = $(".container img").height();
var gap = (imgHeight - conHeight) / 2;
$(".container img").css("margin-top", -gap);
http://jsfiddle.net/x86Q7/2/
链接地址: http://www.djcxy.com/p/15772.html上一篇: 阻止额外的利润
下一篇: CSS图片大小,如何填充,不能拉伸?