使用CSS调整大小和裁剪图像
我想调整大小并裁剪未知尺寸的图片,只需使用CSS。图片应该调整大小/裁剪,以完全填充已知尺寸的容器,尽可能少地截断图片。
I'd like to resize and crop an image of unknown dimensions, just with css. The image should be resized/cropped to completely fill a container of known dimensions, cutting off as little of the image as possible.
此外,如果图片被裁剪,例如,确定应该显示图像的中心,而不是左上角。
Also, if an image is cropped then I'd like to determine, for example, that the center of the image should be shown, not the top left.
我做了一个jsfiddle说明问题: http://jsfiddle.net/q9jFx/
I made a jsfiddle illustrating the issue: http://jsfiddle.net/q9jFx/
例如,我可以将图片宽度设置为100%,但如果图片宽度大于高度,则无法使用。
I can, for example, set image width to 100%, but that doesn't work if the image is wider than it is tall.
.container { width: 180px; height: 160px; overflow: hidden; border:red solid 2px }
.container img { width:100%}
<div class="container">
<img src="the_src" alt="alt" />
</div>
使用CSS background
属性与 background-size
和 background-position
属性。
The only way you can achieve this only using css is to use the CSS background
property combining it with the background-size
and background-position
properties.
查看此 FIDDLE
SEE THIS FIDDLE
有关这些属性的更多信息:
背景位置
background-size
More information for these properties :
background-position
background-size
HTML: / p>
HTML:
<div class="container" style="background-image:url(http://www.recipestap.com/wp-content/plugins/wp-o-matic/cache/af4e1_ap.jpg)"></div>
<div class="container" style="background-image:url(http://3.bp.blogspot.com/-LAfvYIuz6c4/UpQxIe-FlmI/AAAAAAAAAcE/DVeCw1W6Yu4/s320/Eggless+Mini+Apple+Pie.JPG)"></div>
CSS:
.container {
width: 180px;
height: 160px;
border:red solid 2px;
/* add following */
background-size:cover;
background-position:50% 50%;
}
如果由于SEO原因或其他原因,您真的需要< img>
需要JS来面对您可能遇到的所有情况。
If you realy need the <img>
tag for SEO reasons or other, you will need JS to face all the cases you may come through.
CASE 1:图像比宽比容器
使用 height:100%;
和 width:auto;
CASE 2:图片比例比容器高
使用 :100%;
和 height:auto;
then JS或 display:table;
display:table-cell
到verticaly中心的容器中的图像。
CASE 2 : image ratio is heigher than the container
Use width:100%;
and height:auto;
then JS or display:table;
/display:table-cell
to verticaly center the image in container.
与 background
CSS技术相比,它相当重。
I have used this technique on some projects but it is pretty heavy compared to the background
CSS technique.