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

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

问题描述

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

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

但是如果我用css设置宽度和高度(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.

如何使用 CSS 将图像填充到特定大小,并且不拉伸?

How to Fill images to a specific size using CSS, and not stretching it?

填充和拉伸图像的示例:

Example of fill and stretching image:

原始图片:

拉伸图像:

填充图像:

请注意,在上面的填充图像示例中:首先,图像被调整到 150x255(保持纵横比),然后,它裁剪到 150x100.>

Please note that in the Filled image example above: first, image is resized to 150x255 (maintained aspect ratio), and then, it cropped to 150x100.

推荐答案

您可以使用 css 属性 object-fit.

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" />

在这里查看示例

IE 有一个 polyfill:https://github.com/anselmh/object-fit

There's a polyfill for IE: https://github.com/anselmh/object-fit

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

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