CSS图片大小,如何填充,不拉伸? [英] CSS Image size, how to fill, not stretch?

查看:1983
本文介绍了CSS图片大小,如何填充,不拉伸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图片,我想设置它的具体宽度和高度(以像素为单位)

I have an image, and I want to set it a specific width and height (in pixels)

但如果我使用css设置宽度和高度c $ c> width:150px; height:100px ),图像将被拉伸,可能是丑陋的。

But If I set width and height using css (width:150px; height:100px), image will be stretched, and It may be ugly.

如何<

填充和拉伸图片示例:

原始图片:

拉伸图片:

填充图片:

请注意上面的填充图片示例:首先,将图片调整为150x255(保持的宽高比),然后将其裁剪成150x100。

推荐答案

如果你想使用图像作为CSS背景,有一个优雅的解决方案。只需在 background-size CSS3中使用 cover 属性。

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/ (使用封面)

http://jsfiddle.net/HZ2FT/ (使用包含)

根据Thomas Fuchs的快速指南,这种方法的优点是对视网膜显示屏的友好。 http://cl.ly/0v2u190o110R

This approach has the advantage of being friendly to Retina displays as per Thomas Fuchs' quick guide. http://cl.ly/0v2u190o110R

值得一提的是浏览器支持对于这两个属性不包括IE6-8。 http://www.quirksmode.org/css/background.html

It's worth mentioning that browser support for both attributes excludes IE6-8. http://www.quirksmode.org/css/background.html

这篇关于CSS图片大小,如何填充,不拉伸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆