CSS 图像大小,如何填充,而不是拉伸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11757537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:39:23  来源:igfitidea点击:

CSS Image size, how to fill, not stretch?

cssimage

提问by Mahdi Ghiasi

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.

但是如果我使用 css( width:150px; height:100px)设置宽度和高度,图像会被拉伸,并且可能很难看。

How to Fillimages to a specific size using CSS, and not stretchingit?

如何使用 CSS图像填充到特定大小,而不是拉伸它?

Example of fill and stretching image:

填充和拉伸图像的示例:

Original Image:

原图:

Original

原来的

Stretched Image:

拉伸图像:

Stretched

拉伸

Filled Image:

填充图像:

Filled

填充

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

请注意,在上面的填充图像示例中:首先将图像调整为 150x255(保持纵横比),然后将其裁剪为 150x100。

采纳答案by Marcelo De Polli

If you want to use the image as a CSS background, there is an elegant solution. Simply use coveror containin the background-sizeCSS3 property.

如果您想将图像用作 CSS 背景,有一个优雅的解决方案。只需在CSS3 属性中使用cover或 即可。containbackground-size

.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 coverwill give you a scaled up image, containwill give you a scaled down image. Both will preserve the pixel aspect ratio.

虽然cover会给你一个放大的图像,contain会给你一个缩小的图像。两者都将保留像素纵横比。

http://jsfiddle.net/uTHqs/(using cover)

http://jsfiddle.net/uTHqs/(使用封面)

http://jsfiddle.net/HZ2FT/(using contain)

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

This approach has the advantage of being friendly to Retina displays as per Thomas Fuchs' quick guide.

根据Thomas Fuchs 的快速指南,这种方法的优点是对 Retina 显示器友好

It's worth mentioning that browser support for both attributes excludes IE6-8.

值得一提的是,浏览器对这两个属性的支持不包括 IE6-8。

回答by afonsoduarte

You can use the css property object-fit.

您可以使用 css 属性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

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

回答by Hakan F?st?k

Enhancementon the above answer by @afonsoduarte(NOTthe accepted one).
in case you are using bootstrap

增强通过@afonsoduarte以上回答不是已接受的)
如果您正在使用引导程序



有以下三个区别:


  1. Providing width:100%on the style.
    This is helpful if you are using bootstrapand want the image to stretch all the available width.

  2. 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 */
    }
    
  3. By the way, there is NO need to provide the heightand widthattributes on the imageelement because they will be overridden by the style.
    so it is enough to write something like this.

    <img class="cover" src="url to img ..."  />
    
  1. 提供width:100%样式。
    如果您使用引导程序并希望图像拉伸所有可用宽度,这将很有帮助。

  2. 指定height属性是可选的,您可以根据需要删除/保留它

    .cover {
       object-fit: cover;
       width: 100%;
       /*height: 300px;  optional, you can remove it, but in my case it was good */
    }
    
  3. 顺便说一下,不需要在元素上提供heightwidth属性,image因为它们会被样式覆盖。
    所以写这样的东西就足够了。

    <img class="cover" src="url to img ..."  />
    

回答by Dominic Green

The only real way is to have a container around your image and use overflow:hidden:

唯一真正的方法是在您的图像周围放置一个容器并使用overflow:hidden

HTML

HTML

<div class="container"><img src="ckk.jpg" /></div>

CSS

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:

在 CSS 中做你想做的事情并使图像居中是一种痛苦,jquery 中有一个快速修复,例如:

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://jsfiddle.net/x86Q7/2/

回答by J.T. Houtenbos

CSS solution no JS and no background image:

CSS 解决方案没有 JS 和没有背景图像:

Method 1 "margin auto" ( IE8+ - NOT FF!):

方法 1“自动保证金”(IE8+ - NOT FF!):

div{
  width:150px; 
  height:100px; 
  position:relative;
  overflow:hidden;
}
div img{
  position:absolute; 
  top:0; 
  bottom:0; 
  margin: auto;
  width:100%;
}
<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>

<p>Wrapped:</p>
<div>
  <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>

http://jsfiddle.net/5xjr05dt/

http://jsfiddle.net/5xjr05dt/

Method 2 "transform" ( IE9+ ):

方法2“转换”(IE9+):

div{
  width:150px; 
  height:100px; 
  position:relative;
  overflow:hidden;
}

div img{
  position:absolute; 
  width:100%;
  top: 50%;
  -ms-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}
<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>

<p>Wrapped:</p>
<div>
  <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>

http://jsfiddle.net/5xjr05dt/1/

http://jsfiddle.net/5xjr05dt/1/

Method 2 can be used to center an image in a fixed width / height container. Both can overflow - and if the image is smaller than the container it will still be centered.

方法 2 可用于将图像居中放置在固定宽度/高度的容器中。两者都可能溢出 - 如果图像小于容器,它仍将居中。

http://jsfiddle.net/5xjr05dt/3/

http://jsfiddle.net/5xjr05dt/3/

Method 3 "double wrapper" ( IE8+ - NOT FF! ):

方法 3“双重包装器”(IE8+ - NOT FF!):

.outer{
  width:150px; 
  height:100px; 
  margin: 200px auto; /* just for example */
  border: 1px solid red; /* just for example */
  /* overflow: hidden; */ /* TURN THIS ON */
  position: relative;
}
.inner { 
    border: 1px solid green; /* just for example */
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    display: table;
    left: 50%;
}
.inner img {
    display: block;
    border: 1px solid blue; /* just for example */
    position: relative;
    right: 50%;
    opacity: .5; /* just for example */
}
<div class="outer">
  <div class="inner">
     <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
  </div>
</div>

http://jsfiddle.net/5xjr05dt/5/

http://jsfiddle.net/5xjr05dt/5/

Method 4 "double wrapper AND double image" ( IE8+ ):

方法 4“双重包装和双重图像”(IE8+):

.outer{
  width:150px; 
  height:100px; 
  margin: 200px auto; /* just for example */
  border: 1px solid red; /* just for example */
  /* overflow: hidden; */ /* TURN THIS ON */
  position: relative;
}
.inner { 
    border: 1px solid green; /* just for example */
    position: absolute;
    top: 50%;
    bottom: 0;
    display: table;
    left: 50%;
}
.inner .real_image {
    display: block;
    border: 1px solid blue; /* just for example */
    position: absolute;
    bottom: 50%;
    right: 50%;
    opacity: .5; /* just for example */
}

.inner .placeholder_image{
  opacity: 0.1; /* should be 0 */
}
<div class="outer">
  <div class="inner">
    <img class="real_image" src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
    <img class="placeholder_image"  src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
  </div>
</div>

http://jsfiddle.net/5xjr05dt/26/

http://jsfiddle.net/5xjr05dt/26/

  • Method 1 has slightly better support - you have to set the width OR height of image!
  • With the prefixes method 2 also has decent support ( from ie9 up ) - Method 2 has no support on Opera mini!
  • Method 3 uses two wrappers - can overflow width AND height.
  • Method 4 uses a double image ( one as placeholder ) this gives some extra bandwidth overhead, but even better crossbrowser support.
  • 方法 1 的支持稍微好一些 - 您必须设置图像的宽度或高度!
  • 使用前缀方法 2 也有不错的支持(从 ie9 开始) - 方法 2 不支持 Opera mini!
  • 方法 3 使用两个包装器 - 可以溢出宽度和高度。
  • 方法 4 使用双重图像(一个作为占位符)这会带来一些额外的带宽开销,但甚至更好的跨浏览器支持。

Method 1 and 3 don't seem to work with Firefox

方法 1 和 3 似乎不适用于 Firefox

回答by earl3s

Another solution is to put the image in a container with the desired width and height. Using this method you would not have to set the image as a background image of an element.

另一种解决方案是将图像放入具有所需宽度和高度的容器中。使用此方法,您不必将图像设置为元素的背景图像。

Then you can do this with an imgtag and just set a max-width and max-height on the element.

然后你可以用一个img标签来做到这一点,只需在元素上设置一个 max-width 和 max-height 。

CSS:

CSS:

.imgContainer {
    display: block;
    width: 150px; 
    height: 100px;
}

.imgContainer img {
    max-width: 100%;
    max-height: 100%;
}

HTML:

HTML:

<div class='imgContainer'>
    <img src='imagesrc.jpg' />
</div>

Now when you change the size of the container the image will automatically grow as large as it can without going outside the bounds or distorting.

现在,当您更改容器的大小时,图像将自动尽可能大而不会超出边界或扭曲。

If you want to center the imagevertically and horizontally you can change the container css to:

如果要垂直和水平居中图像,可以将容器 css 更改为:

.imgContainer {
    display: table-cell;
    width: 150px; 
    height: 100px;
    text-align: center;
    vertical-align: middle;
}

Here is a JS Fiddle http://jsfiddle.net/9kUYC/2/

这是一个 JS Fiddle http://jsfiddle.net/9kUYC/2/

回答by ramdog

Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.

基于@Dominic Green 使用 jQuery 的回答,这里有一个解决方案,适用于宽度大于高度或大于宽度的图像。

http://jsfiddle.net/grZLR/4/

http://jsfiddle.net/grZLR/4/

There is probably a more elegant way of doing the JavaScript, but this does work.

可能有一种更优雅的 JavaScript 方式,但这确实有效。

function myTest() {
  var imgH = $("#my-img").height();
  var imgW = $("#my-img").width();
  if(imgW > imgH) {
    $(".container img").css("height", "100%");
    var conWidth = $(".container").width();
    var imgWidth = $(".container img").width();
    var gap = (imgWidth - conWidth)/2;
    $(".container img").css("margin-left", -gap);
  } else {
    $(".container img").css("width", "100%");
    var conHeight = $(".container").height();
    var imgHeight = $(".container img").height();
    var gap = (imgHeight - conHeight)/2;
    $(".container img").css("margin-top", -gap);
  }
}
myTest();

回答by dmegatool

  • Not using css background
  • Only 1 div to clip it
  • Resized to minimum width than keep correct aspect ratio
  • Crop from center (vertically and horizontally, you can adjust that with the top, lef & transform)
  • 不使用css背景
  • 只有 1 div 来剪辑它
  • 调整到最小宽度而不是保持正确的纵横比
  • 从中心裁剪(垂直和水平,您可以使用顶部、左侧和变换进行调整)

Be careful if you're using a theme or something, they'll often declare img max-width at 100%. You got to make none. Test it out :)

如果您使用主题或其他东西,请小心,他们通常会声明 img max-width 为 100%。你必须什么都不做。测试一下:)

https://jsfiddle.net/o63u8sh4/

https://jsfiddle.net/o63u8sh4/

<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>

<p>Wrapped:</p>
<div>
    <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>


div{
  width:150px; 
  height:100px; 
  position:relative;
  overflow:hidden;
}
div img{
  min-width:100%;
  min-height:100%;
  height:auto;
  position:relative;
  top:50%;
  left:50%;
  transform:translateY(-50%) translateX(-50%);
}

回答by Nodirabegimxonoyim

I think it's quite late for this answer. Anyway hope this will help somebody in the future. I faced the problem positioning the cards in angular. There are cards displayed for array of events. If image width of the event is big for card, the image should be shown by cropping from two sides and height of 100 %. If image height is long, images' bottom part is cropped and width is 100 %. Here is my pure css solution for this:

我认为这个答案已经很晚了。无论如何,希望这会在将来对某人有所帮助。我遇到了以角度定位卡片的问题。有显示事件数组的卡片。如果卡片的事件图像宽度较大,则图像应从两侧裁剪显示,高度为 100%。如果图像高度很长,图像的底部将被裁剪,宽度为 100%。这是我的纯 css 解决方案:

enter image description here

在此处输入图片说明

HTML:

HTML:

 <span class="block clear img-card b-b b-light text-center" [ngStyle]="{'background-image' : 'url('+event.image+')'}"></span>

CSS

CSS

.img-card {
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
width: 100%;
overflow: hidden;
}

回答by Aidan Feldman

I helped build a jQuery plugin called Fillmore, which handles the background-size: coverin browsers that support it, and has a shim for those that don't. Give it a look!

我帮助构建了一个名为Fillmore的 jQuery 插件,它处理background-size: cover支持它的浏览器,并为那些不支持的浏览器提供一个垫片。看看吧!