如何自动调整图像大小以适应div容器

时间:2022-11-13 10:43:20

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining it's width:height ratio?

如何自动调整一个大图像的大小,使它适合一个较小的宽度div容器,同时保持它的宽度:高度比?


Example: *.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.

例如:*.com——当一个图像被插入到编辑器面板中,并且这个图像太大而无法嵌入页面时,这个图像就会自动调整大小。

28 个解决方案

#1


1405  

Do not apply an explicit width or height to the image tag. Instead, give it:

不要对图像标记应用显式的宽度或高度。相反,给它:

max-width:100%;max-height:100%;

Also, height: auto; if you want to specify a width only.

同时,高度:汽车;如果只指定宽度。

Example: http://jsfiddle.net/xwrvxser/1/

例如:http://jsfiddle.net/xwrvxser/1/

img {    max-width: 100%;    max-height: 100%;}.portrait {    height: 80px;    width: 30px;}.landscape {    height: 30px;    width: 80px;}.square {    height: 75px;    width: 75px;}
Portrait Div<div class="portrait">    <img src="http://i.stack.imgur.com/xkF9Q.jpg"></div>Landscape Div<div class="landscape">    <img src="http://i.stack.imgur.com/xkF9Q.jpg"></div>Square Div<div class="square">    <img src="http://i.stack.imgur.com/xkF9Q.jpg"></div>

#2


228  

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

turns out there's another way to do this.

其实还有另一种方法。

<img style='height: 100%; width: 100%; object-fit: contain'/> 

will do the work. It's CSS3 stuff.

将做的工作。CSS3的东西。

Fiddle: http://jsfiddle.net/mbHB4/7364/

小提琴:http://jsfiddle.net/mbHB4/7364/

#3


92  

Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.

目前没有办法以确定的方式正确地完成这一操作,使用固定大小的图像,如jpeg或PNG文件。

To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.

要按比例调整图像的大小,必须将高度或宽度设置为“100%”,但不能同时设置。如果你将两者都设置为“100%”,你的图像将被拉伸。

Choosing whether to do height or width depends on your image and container dimensions:

选择高度或宽度取决于您的图像和容器尺寸:

  1. If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
  2. 如果你的图像和容器都是“肖像型”或“风景型”(分别比它们宽或比它们高宽),那么哪个高度或宽度是“%100”并不重要。
  3. If your image is portrait, and your container is landscape, you must set height="100%" on the image.
  4. 如果你的图像是竖屏,而你的容器是风景,你必须在图像上设置高度="100%"。
  5. If your image is landscape, and your container is portrait, you must set width="100%" on the image.
  6. 如果图像是横向的,容器是纵向的,那么必须在图像上设置width="100%"。

If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.

如果您的图像是SVG(一种可变大小的矢量图像格式),则可以自动展开以适应容器。

You just have to ensure that the SVG file has none of these properties set in the <svg> tag:

您只需确保SVG文件在< SVG >标记中没有设置任何这些属性:

heightwidthviewbox

Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.

大多数矢量绘图程序在导出SVG文件时都会设置这些属性,因此每次导出时都必须手动编辑文件,或者编写脚本。

#4


63  

Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div.The html:

这是一种解决方案,可以在div中垂直和水平地对齐img,而不会有任何拉伸,即使所提供的图像太小或太大,不适合div。

<div id="myDiv">  <img alt="Client Logo" title="Client Logo" src="Imagelocation" /></div>

The CSS:

CSS:

#myDiv {  height:104px;  width:140px;}#myDiv img{  max-width:100%;   max-height:100%;  margin:auto;  display:block;}

The JQuery:

JQuery:

var logoHeight = $('#myDiv img').height();    if (logoHeight < 104) {        var margintop = (104 - logoHeight) / 2;        $('#myDiv img').css('margin-top', margintop);    }

I hope this helps you guys out

我希望这能帮到你们

#5


36  

Make it simple!

让它简单!

Give the container a fixed height and then for the img tag inside it set width and max-height.

给容器一个固定的高度,然后为里面的img标签设置宽度和最大高度。

<div style="height: 250px">     <img src="..." alt=" " style="width: 100%;max-height: 100%" /></div>

Difference is that you set the width to be 100% not the max-width.

不同之处在于您将宽度设置为100%而不是最大宽度。

#6


19  

Check out my solution: http://codepen.io/petethepig/pen/dvFsA

看看我的解决方案:http://codepen.io/petethepig/pen/dvFsA

It's written in pure CSS, without any JS code.It can handle images of any size and any orientation.

它是用纯CSS编写的,没有任何JS代码。它可以处理任何大小和方向的图像。

Given such HTML:

鉴于这样的HTML:

<div class="image">  <div class="trick"></div>  <img src="http://placekitten.com/415/200"/></div>

CSS code would be:

CSS代码是:

.image {  font-size: 0;  text-align: center;  width: 200px;  /* Container's dimensions */  height: 150px;}img {  display: inline-block;  vertical-align: middle;  max-height: 100%;  max-width: 100%;}.trick {  display: inline-block;  vertical-align: middle;  height: 150px;}

#7


17  

You can set the image as the background to a div, then use the css background-size property

您可以将图像设置为div的背景,然后使用css background-size属性

background-size: cover;

and it will "Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area" -w3schools.com

它将“将背景图像缩放到尽可能大,使背景区域完全被背景图像覆盖。”背景图像的某些部分可能不在背景定位区域内。

#8


11  

A beautiful hack.

一个美丽的黑客。

You have two ways of making the image responsive.

你有两种方法使图像响应。

  1. When an image is a background image.
  2. 当图像是背景图像时。
#container{    width: 300px;    height: 300px;    background-image: url(http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);    background-size: cover;    background-repeat: no-repeat;    background-position: center;}<div id="container"><div>

Run it here

运行它在这里


But one should use img tag to put images as it is better than background-image in terms of SEO as you can write keyword in the alt of the img tag. So here is you can make the image responsive.

  1. When image is in img tag.
  2. 当图像在img标签中。
#container{    max-width: 400px;    overflow: hidden;}img{    width: 100%;    object-fit: contain;}<div id="container">   <img src="http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/><div>

Run it here

运行它在这里

#9


9  

This solution doesn't stretch the image and fills the whole container, but it cuts some of the image.

这个解决方案不会拉伸图像并填充整个容器,但是它会剪切一些图像。

html

html

 <div><img src="/images/image.png"></div>

CSS

CSS

div {  width: 100%;  height: 10em;  overflow: hidden;img {  min-width: 100%;  min-height: 100%;}

#10


8  

I just published a jQuery plugin that do exactly what you need with a lot of options :

我刚刚发布了一个jQuery插件,它可以满足你的很多选择:

https://github.com/GestiXi/image-scale

https://github.com/GestiXi/image-scale

Usage:

用法:

HTML

HTML

<div class="image-container">  <img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg"></div>

JS

JS

$(function() {  $("img.scale").imageScale();});

#11


6  

I have much better solution without need of any JS. It is fully responsive and I use it a lot. You often need to fit image of any aspect ratio to container element with specified aspect ratio. And having whole this thing fully responsive is a must.

我有更好的解决方案,不需要任何JS。它是完全响应的,我经常使用它。您通常需要将任何纵横比的图像与具有指定纵横比的容器元素匹配。让整个事情完全响应是必须的。

/* For this demo only */.container {  max-width: 300px;  margin: 0 auto;}.img-frame {  box-shadow: 3px 3px 6px rgba(0,0,0,.15);  background: #ee0;  margin: 20px auto;}/* This is for responsive container with specified aspect ratio */.aspect-ratio {  position: relative;}.aspect-ratio-1-1 {  padding-bottom: 100%;}.aspect-ratio-4-3 {  padding-bottom: 75%;}.aspect-ratio-16-9 {  padding-bottom: 56.25%;}/* This is the key part - position and fit the image to the container */.fit-img {  position: absolute;  top: 0;  right: 0;  bottom: 0;  left: 0;  margin: auto;  max-width: 80%;  max-height: 90%}.fit-img-bottom {  top: auto;}.fit-img-tight {  max-width: 100%;  max-height: 100%}
<div class="container">  <div class="aspect-ratio aspect-ratio-1-1 img-frame">    <img src="//placehold.it/400x300" class="fit-img" alt="sample">  </div>  <div class="aspect-ratio aspect-ratio-4-3 img-frame">    <img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample">  </div>  <div class="aspect-ratio aspect-ratio-16-9 img-frame">    <img src="//placehold.it/400x400" class="fit-img" alt="sample">  </div>    <div class="aspect-ratio aspect-ratio-16-9 img-frame">    <img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample">  </div>  </div>

You can set max-width and max height independently, image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (eg. for product picture on infinite white background you can position it to center bottom easily)

您可以独立设置最大宽度和最大高度,图像将尊重最小的一个(取决于图像的值和长宽比)。您还可以将图像设置为您想要的对齐(例如)。在无限白色背景下的产品图片你可以很容易地将它定位到中心底部

#12


4  

The accepted answer from Thorn007 doesn't work when the image is too small.
To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.

索恩007的公认答案在图像太小时不起作用。为了解决这个问题,我添加了一个比例因子。通过这种方式,它将图像放大并填充div容器。

Example :

例子:

<div style="width:400px; height:200px;">  <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" /></div>

notes:
1/ for webkit you must add -webkit-transform:scale(4); -webkit-transform-origin:left top; in the style.
2/ with a scale factor of 4, you have max-width = 400/4 = 100 and max-height = 200/4 = 50
3/ an alternate solution is to set max-width and max-height at 25%, it's even simpler

notes: 1/对于webkit,你必须添加-webkit-transform:scale(4);-webkit-transform-origin:左前;的风格。2/如果比例因子为4,则max-width = 400/4 = 100, max-height = 200/4 = 50 / 3/一个替代的解决方案是将max-width和max-height设为25%,这样更简单

#13


4  

The code below is adapted from above and tested by me using an image called storm.jpgThis is the complete HTML code for a simple page that displays the image. This works perfect and was tested by me with www.resizemybrowser.com. Put the CSS code at the top of your HTML code, underneath your head section. Put the the picture code wherever you want the picture.

下面的代码改编自上面的代码,并由我使用一个名为storm.jpg的图像进行测试。这是完美的,我用www.resizemybrowser.com来测试。把CSS代码放在你的HTML代码的顶部,在你的头部下面。把图片代码放在你想要的地方。

<html><head>  <style type="text/css">  #myDiv   {    height:auto;    width:auto;  }  #myDiv img  {    max-width:100%;     max-height:100%;    margin:auto;    display:block;  } </style></head><body>    <div id="myDiv">        <img src="images/storm.jpg">    </div></body></html>

#14


3  

I centered and scaled proportionally an image inside a hyperlink both horizontally and vertically this way:

我以这种方式在一个超链接内水平和垂直地居中并按比例缩放一个图像:

#link {    border: 1px solid blue;    display: table-cell;    height: 100px;    vertical-align: middle;    width: 100px;}#link img {    border: 1px solid red;    display: block;    margin-left: auto;    margin-right: auto;    max-height: 60px;    max-width: 60px;}

Tested in IE, Firefox, Safari.

在IE, Firefox, Safari中测试。

More info about centering is here.

更多关于定心的信息在这里。

#15


3  

Give the height and width you need for your image to the div that contains the < img> tag.don't forget to give the height/width in proper style tag.In the < img> tag, give the max-height and max-width as 100%.

将图像所需的高度和宽度指定给包含< img>标记的div。别忘了在合适的样式标签上注明高度/宽度。在< img>标签中,最大高度和最大宽度为100%。

<div style="height:750px; width:700px;">    <img alt="That Image" style="max-height:100%; max-width:100%;" src=""></div>

you can add the details in appropriate classes after you got it right.

您可以在正确的类中添加细节。

#16


3  

<style type="text/css"> #container{text-align:center;width: 100%;height: 200px; /*set height*/margin: 0px;padding: 0px;background-image:url('../assets/images/img.jpg');background-size: content; /*scaling down large image to a div*/background-repeat:no-repeat;background-position:center;}</style><div id="container><!--inside container--></div>

#17


3  

You have to tell the browser the height of where you are placing it.

你必须告诉浏览器你放置它的高度。

.example {  height: 220px; //DEFINE HEIGHT  background:url('../img/example.png');  background-size: 100% 100%;  background-repeat: no-repeat;}

#18


3  

Edit: Previous table based image positioning had issues in IE11 (max-height doesn't work in display:table elements). I've replaced it with inline based positioning which not only works fine in both IE7 and IE11, but also requires less code.

编辑:以前基于表的图像定位在IE11中有问题(最大高度在显示中不起作用:表元素)。我已经用基于内联的定位替换了它,它不仅在IE7和IE11中都很好用,而且需要更少的代码。


Here is my take on the subject. It'll only work if the container has specified size (max-width and max-height don't seem to get along with containers that don't have concrete size), but I wrote the css in a way that allows it to be reused (add picture-frame class and px125 size class to your existing container).

这是我对这个问题的看法。只有当容器具有指定的大小(最大宽度和最大高度似乎不能与没有具体大小的容器共存)时,它才会工作,但是我以允许重用它的方式编写css(在现有容器中添加picture-frame类和px125 size类)。

In css:

在css中:

.picture-frame{    vertical-align:top;    display:inline-block;    text-align:center;}.picture-frame.px125{    width:125px;    height:125px;    line-height:125px;}.picture-frame img{    margin-top:-4px; /* inline images have a slight offset for some reason when positioned using vertical-align */    max-width:100%;    max-height:100%;    display:inline-block;    vertical-align: middle;    border:0; /* Remove border on imgs enclosed in anchors in IE */}

And in html:

在html中:

<a href="#" class="picture-frame px125">    <img src="http://i.imgur.com/lesa2wS.png"/></a>

DEMO

/* Main style */.picture-frame{    vertical-align:top;    display:inline-block;    text-align:center;}.picture-frame.px32{    width:32px;    height:32px;    line-height:32px;}.picture-frame.px125{    width:125px;    height:125px;    line-height:125px;}.picture-frame img{    margin-top:-4px; /* inline images have a slight offset for some reason when positioned using vertical-align */    max-width:100%;    max-height:100%;    display:inline-block;    vertical-align: middle;    border:0; /* Remove border on imgs enclosed in anchors in IE */}/* Extras */.picture-frame{    padding: 5px;}.frame{    border:1px solid black;}
<p>32px</p><a href="#" class="picture-frame px32 frame">    <img src="http://i.imgur.com/lesa2wS.png"/></a><a href="#" class="picture-frame px32 frame">    <img src="http://i.imgur.com/kFMJxdZ.png"/></a><a href="#" class="picture-frame px32 frame">    <img src="http://i.imgur.com/BDabZj0.png"/></a><p>125px</p><a href="#" class="picture-frame px125 frame">    <img src="http://i.imgur.com/lesa2wS.png"/></a><a href="#" class="picture-frame px125 frame">    <img src="http://i.imgur.com/kFMJxdZ.png"/></a><a href="#" class="picture-frame px125 frame">    <img src="http://i.imgur.com/BDabZj0.png"/></a>


Edit: Possible further improvement using JS (upscaling images):

编辑:使用JS(放大图像)可能进一步改进:

function fixImage(img){    var $this = $(img);    var parent = $this.closest('.picture-frame');    if ($this.width() == parent.width() || $this.height() == parent.height())        return;    if ($this.width() > $this.height())        $this.css('width', parent.width() + 'px');    else        $this.css('height', parent.height() + 'px');}$('.picture-frame img:visible').each(function{    if (this.complete)        fixImage(this);    else        this.onload = function(){ fixImage(this) };});

#19


2  

A simple solution ( 4-step fix !!) that seem to work for me , is below. Hope it helps.The example uses the width to determine the overall size, but you can also flip it to use the height instead.

下面是一个简单的解决方案(4步修复!)希望它可以帮助。这个示例使用宽度来确定总体大小,但是您也可以翻转它来使用高度。

  1. Apply CSS styling to the image container ( eg
  2. 将CSS样式应用到图像容器(例如
  3. set the width property to the dimension you want
    • for dimensions use % for relative size,or autoscaling ( based on image container or display ) -use px ( or other ) for a static, or set dimension
    • 对于尺寸,使用%表示相对大小,或自动缩放(基于图像容器或显示)-使用px(或其他)表示静态尺寸或设置尺寸
  4. 将width属性设置为您想要的维度,使用%来表示相对大小,或自动缩放(基于图像容器或显示)—使用px(或其他)来表示静态维度或设置维度
  5. set the height property to automatically adjust, based on the width
  6. 设置高度属性,根据宽度自动调整
  7. ENJOY!
  8. 享受吧!

for example

例如

<img style="width:100%; height:auto;"                            src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"                />

#20


2  

As answered here, you can also use vh units instead of max-height: 100% if it doesn't work on your browser (like Chrome):

正如这里所回答的,您也可以使用vh单元而不是max-height: 100%如果它不能在您的浏览器上工作(如Chrome):

img {    max-height: 75vh;}

#21


1  

All the provided answers, including the accepted one, work only under the assumption that the div wrapper is of a fixed size. So this is how to do it whatever the size of the div wrapper is and this is very useful if you develop a responsive page:

所有提供的答案(包括已接受的答案)只能在假设div包装器是固定大小的情况下工作。这就是如何处理div包装器的大小这是非常有用的如果你开发一个响应式页面:

Write these declarations inside your DIV selector:

在您的DIV选择器中写入以下声明:

width : 8.33% /* or whatever percentage you want your div to take*/max-height : anyValueYouWant /*(in px or %)*/ 

Then put these declarations inside your IMG selector:

然后将这些声明放在IMG选择器中:

width : "100%" /* obligatory */max-height :  anyValueYouWant /*(in px or %)*/ 

VERY IMPORTANT:

非常重要:

The value of maxHeight must be the same for both the DIV and IMG selectors.

对于DIV和IMG选择器,maxHeight的值必须相同。

#22


0  

The solution is easy with a bit of maths...

解决方法很简单,只需一点数学知识……

Just put the image in a div and then in the html file where you specify the image set the width and height values in percentages using the pixel values of the image to calculate the exact ratio of width to height.

只需将图像放在div中,然后在html文件中指定图像,使用图像的像素值以百分比设置宽度和高度值,计算宽度和高度的精确比值。

For example, say you have an image that has a width of 200 pixels and a height of 160 pixels. You can safely say that the width value will be 100% because it is the larger value. To then calculate the height value you simply divide the height by the width which gives the percentage value of 80%. In the code it will look something like this...

例如,假设有一个图像宽度为200像素,高度为160像素。您可以放心地说宽度值将为100%,因为它是较大的值。要计算高度值,只需将高度除以宽度,宽度为80%。代码是这样的……

#23


0  

check my ans https://*.com/a/36712112/2439715

检查我的ans https://*.com/a/36712112/2439715

img{    width: 100%;    max-width: 800px;}

#24


0  

A simple solution is to use flex-box. Define the container's CSS to:

一个简单的解决方案是使用浮动框。将容器的CSS定义为:

.container{    display: flex;    justify-content: center;    align-items: center;    align-content: center;    overflow: hidden;    /*any custom height*/}

Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved. Cheers.

将所包含的图像宽度调整为100%,您应该在容器中得到一个以保存的尺寸为中心的图像。欢呼。

#25


-1  

Simplest way to do this is

最简单的方法是

by using object-fit

通过使用object-fit

<div class="container">  <img src="path/to/image.jpg"></div>.container{   height: 300px;}.container img{  height:100%;  width:100%;  object-fit: cover;}

If your using bootstrap just add the img-responsive class and changed to

如果您使用的是bootstrap,那么只需添加响应img的类并将其更改为

.container img{      object-fit: cover;    }

#26


-1  

Or you can simply use:

或者你可以简单地使用:

background-position:center;background-size:cover;

Now the image will take all the space of the div.

现在图像将占用div的所有空间。

#27


-1  

The following works perfectly for me:

以下是最适合我的:

img{   height: 99999px;   object-fit:contain;   max-height: 100%;   max-width: 100%;       display: block;   margin: auto auto;}

#28


-5  

Define div simply

定义div简单

   div.headerimg1 {       position: absolute;       top: 290px;       left: 81px;       width: 389px;            height: 349px;}<div class="headerimg1"><img src="" style="max-height:100%;height:auto;width:100%;max-width:100%;margin:auto;display:inline;"></div>

#1


1405  

Do not apply an explicit width or height to the image tag. Instead, give it:

不要对图像标记应用显式的宽度或高度。相反,给它:

max-width:100%;max-height:100%;

Also, height: auto; if you want to specify a width only.

同时,高度:汽车;如果只指定宽度。

Example: http://jsfiddle.net/xwrvxser/1/

例如:http://jsfiddle.net/xwrvxser/1/

img {    max-width: 100%;    max-height: 100%;}.portrait {    height: 80px;    width: 30px;}.landscape {    height: 30px;    width: 80px;}.square {    height: 75px;    width: 75px;}
Portrait Div<div class="portrait">    <img src="http://i.stack.imgur.com/xkF9Q.jpg"></div>Landscape Div<div class="landscape">    <img src="http://i.stack.imgur.com/xkF9Q.jpg"></div>Square Div<div class="square">    <img src="http://i.stack.imgur.com/xkF9Q.jpg"></div>

#2


228  

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

turns out there's another way to do this.

其实还有另一种方法。

<img style='height: 100%; width: 100%; object-fit: contain'/> 

will do the work. It's CSS3 stuff.

将做的工作。CSS3的东西。

Fiddle: http://jsfiddle.net/mbHB4/7364/

小提琴:http://jsfiddle.net/mbHB4/7364/

#3


92  

Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.

目前没有办法以确定的方式正确地完成这一操作,使用固定大小的图像,如jpeg或PNG文件。

To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.

要按比例调整图像的大小,必须将高度或宽度设置为“100%”,但不能同时设置。如果你将两者都设置为“100%”,你的图像将被拉伸。

Choosing whether to do height or width depends on your image and container dimensions:

选择高度或宽度取决于您的图像和容器尺寸:

  1. If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
  2. 如果你的图像和容器都是“肖像型”或“风景型”(分别比它们宽或比它们高宽),那么哪个高度或宽度是“%100”并不重要。
  3. If your image is portrait, and your container is landscape, you must set height="100%" on the image.
  4. 如果你的图像是竖屏,而你的容器是风景,你必须在图像上设置高度="100%"。
  5. If your image is landscape, and your container is portrait, you must set width="100%" on the image.
  6. 如果图像是横向的,容器是纵向的,那么必须在图像上设置width="100%"。

If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.

如果您的图像是SVG(一种可变大小的矢量图像格式),则可以自动展开以适应容器。

You just have to ensure that the SVG file has none of these properties set in the <svg> tag:

您只需确保SVG文件在< SVG >标记中没有设置任何这些属性:

heightwidthviewbox

Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.

大多数矢量绘图程序在导出SVG文件时都会设置这些属性,因此每次导出时都必须手动编辑文件,或者编写脚本。

#4


63  

Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div.The html:

这是一种解决方案,可以在div中垂直和水平地对齐img,而不会有任何拉伸,即使所提供的图像太小或太大,不适合div。

<div id="myDiv">  <img alt="Client Logo" title="Client Logo" src="Imagelocation" /></div>

The CSS:

CSS:

#myDiv {  height:104px;  width:140px;}#myDiv img{  max-width:100%;   max-height:100%;  margin:auto;  display:block;}

The JQuery:

JQuery:

var logoHeight = $('#myDiv img').height();    if (logoHeight < 104) {        var margintop = (104 - logoHeight) / 2;        $('#myDiv img').css('margin-top', margintop);    }

I hope this helps you guys out

我希望这能帮到你们

#5


36  

Make it simple!

让它简单!

Give the container a fixed height and then for the img tag inside it set width and max-height.

给容器一个固定的高度,然后为里面的img标签设置宽度和最大高度。

<div style="height: 250px">     <img src="..." alt=" " style="width: 100%;max-height: 100%" /></div>

Difference is that you set the width to be 100% not the max-width.

不同之处在于您将宽度设置为100%而不是最大宽度。

#6


19  

Check out my solution: http://codepen.io/petethepig/pen/dvFsA

看看我的解决方案:http://codepen.io/petethepig/pen/dvFsA

It's written in pure CSS, without any JS code.It can handle images of any size and any orientation.

它是用纯CSS编写的,没有任何JS代码。它可以处理任何大小和方向的图像。

Given such HTML:

鉴于这样的HTML:

<div class="image">  <div class="trick"></div>  <img src="http://placekitten.com/415/200"/></div>

CSS code would be:

CSS代码是:

.image {  font-size: 0;  text-align: center;  width: 200px;  /* Container's dimensions */  height: 150px;}img {  display: inline-block;  vertical-align: middle;  max-height: 100%;  max-width: 100%;}.trick {  display: inline-block;  vertical-align: middle;  height: 150px;}

#7


17  

You can set the image as the background to a div, then use the css background-size property

您可以将图像设置为div的背景,然后使用css background-size属性

background-size: cover;

and it will "Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area" -w3schools.com

它将“将背景图像缩放到尽可能大,使背景区域完全被背景图像覆盖。”背景图像的某些部分可能不在背景定位区域内。

#8


11  

A beautiful hack.

一个美丽的黑客。

You have two ways of making the image responsive.

你有两种方法使图像响应。

  1. When an image is a background image.
  2. 当图像是背景图像时。
#container{    width: 300px;    height: 300px;    background-image: url(http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);    background-size: cover;    background-repeat: no-repeat;    background-position: center;}<div id="container"><div>

Run it here

运行它在这里


But one should use img tag to put images as it is better than background-image in terms of SEO as you can write keyword in the alt of the img tag. So here is you can make the image responsive.

  1. When image is in img tag.
  2. 当图像在img标签中。
#container{    max-width: 400px;    overflow: hidden;}img{    width: 100%;    object-fit: contain;}<div id="container">   <img src="http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/><div>

Run it here

运行它在这里

#9


9  

This solution doesn't stretch the image and fills the whole container, but it cuts some of the image.

这个解决方案不会拉伸图像并填充整个容器,但是它会剪切一些图像。

html

html

 <div><img src="/images/image.png"></div>

CSS

CSS

div {  width: 100%;  height: 10em;  overflow: hidden;img {  min-width: 100%;  min-height: 100%;}

#10


8  

I just published a jQuery plugin that do exactly what you need with a lot of options :

我刚刚发布了一个jQuery插件,它可以满足你的很多选择:

https://github.com/GestiXi/image-scale

https://github.com/GestiXi/image-scale

Usage:

用法:

HTML

HTML

<div class="image-container">  <img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg"></div>

JS

JS

$(function() {  $("img.scale").imageScale();});

#11


6  

I have much better solution without need of any JS. It is fully responsive and I use it a lot. You often need to fit image of any aspect ratio to container element with specified aspect ratio. And having whole this thing fully responsive is a must.

我有更好的解决方案,不需要任何JS。它是完全响应的,我经常使用它。您通常需要将任何纵横比的图像与具有指定纵横比的容器元素匹配。让整个事情完全响应是必须的。

/* For this demo only */.container {  max-width: 300px;  margin: 0 auto;}.img-frame {  box-shadow: 3px 3px 6px rgba(0,0,0,.15);  background: #ee0;  margin: 20px auto;}/* This is for responsive container with specified aspect ratio */.aspect-ratio {  position: relative;}.aspect-ratio-1-1 {  padding-bottom: 100%;}.aspect-ratio-4-3 {  padding-bottom: 75%;}.aspect-ratio-16-9 {  padding-bottom: 56.25%;}/* This is the key part - position and fit the image to the container */.fit-img {  position: absolute;  top: 0;  right: 0;  bottom: 0;  left: 0;  margin: auto;  max-width: 80%;  max-height: 90%}.fit-img-bottom {  top: auto;}.fit-img-tight {  max-width: 100%;  max-height: 100%}
<div class="container">  <div class="aspect-ratio aspect-ratio-1-1 img-frame">    <img src="//placehold.it/400x300" class="fit-img" alt="sample">  </div>  <div class="aspect-ratio aspect-ratio-4-3 img-frame">    <img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample">  </div>  <div class="aspect-ratio aspect-ratio-16-9 img-frame">    <img src="//placehold.it/400x400" class="fit-img" alt="sample">  </div>    <div class="aspect-ratio aspect-ratio-16-9 img-frame">    <img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample">  </div>  </div>

You can set max-width and max height independently, image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (eg. for product picture on infinite white background you can position it to center bottom easily)

您可以独立设置最大宽度和最大高度,图像将尊重最小的一个(取决于图像的值和长宽比)。您还可以将图像设置为您想要的对齐(例如)。在无限白色背景下的产品图片你可以很容易地将它定位到中心底部

#12


4  

The accepted answer from Thorn007 doesn't work when the image is too small.
To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.

索恩007的公认答案在图像太小时不起作用。为了解决这个问题,我添加了一个比例因子。通过这种方式,它将图像放大并填充div容器。

Example :

例子:

<div style="width:400px; height:200px;">  <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" /></div>

notes:
1/ for webkit you must add -webkit-transform:scale(4); -webkit-transform-origin:left top; in the style.
2/ with a scale factor of 4, you have max-width = 400/4 = 100 and max-height = 200/4 = 50
3/ an alternate solution is to set max-width and max-height at 25%, it's even simpler

notes: 1/对于webkit,你必须添加-webkit-transform:scale(4);-webkit-transform-origin:左前;的风格。2/如果比例因子为4,则max-width = 400/4 = 100, max-height = 200/4 = 50 / 3/一个替代的解决方案是将max-width和max-height设为25%,这样更简单

#13


4  

The code below is adapted from above and tested by me using an image called storm.jpgThis is the complete HTML code for a simple page that displays the image. This works perfect and was tested by me with www.resizemybrowser.com. Put the CSS code at the top of your HTML code, underneath your head section. Put the the picture code wherever you want the picture.

下面的代码改编自上面的代码,并由我使用一个名为storm.jpg的图像进行测试。这是完美的,我用www.resizemybrowser.com来测试。把CSS代码放在你的HTML代码的顶部,在你的头部下面。把图片代码放在你想要的地方。

<html><head>  <style type="text/css">  #myDiv   {    height:auto;    width:auto;  }  #myDiv img  {    max-width:100%;     max-height:100%;    margin:auto;    display:block;  } </style></head><body>    <div id="myDiv">        <img src="images/storm.jpg">    </div></body></html>

#14


3  

I centered and scaled proportionally an image inside a hyperlink both horizontally and vertically this way:

我以这种方式在一个超链接内水平和垂直地居中并按比例缩放一个图像:

#link {    border: 1px solid blue;    display: table-cell;    height: 100px;    vertical-align: middle;    width: 100px;}#link img {    border: 1px solid red;    display: block;    margin-left: auto;    margin-right: auto;    max-height: 60px;    max-width: 60px;}

Tested in IE, Firefox, Safari.

在IE, Firefox, Safari中测试。

More info about centering is here.

更多关于定心的信息在这里。

#15


3  

Give the height and width you need for your image to the div that contains the < img> tag.don't forget to give the height/width in proper style tag.In the < img> tag, give the max-height and max-width as 100%.

将图像所需的高度和宽度指定给包含< img>标记的div。别忘了在合适的样式标签上注明高度/宽度。在< img>标签中,最大高度和最大宽度为100%。

<div style="height:750px; width:700px;">    <img alt="That Image" style="max-height:100%; max-width:100%;" src=""></div>

you can add the details in appropriate classes after you got it right.

您可以在正确的类中添加细节。

#16


3  

<style type="text/css"> #container{text-align:center;width: 100%;height: 200px; /*set height*/margin: 0px;padding: 0px;background-image:url('../assets/images/img.jpg');background-size: content; /*scaling down large image to a div*/background-repeat:no-repeat;background-position:center;}</style><div id="container><!--inside container--></div>

#17


3  

You have to tell the browser the height of where you are placing it.

你必须告诉浏览器你放置它的高度。

.example {  height: 220px; //DEFINE HEIGHT  background:url('../img/example.png');  background-size: 100% 100%;  background-repeat: no-repeat;}

#18


3  

Edit: Previous table based image positioning had issues in IE11 (max-height doesn't work in display:table elements). I've replaced it with inline based positioning which not only works fine in both IE7 and IE11, but also requires less code.

编辑:以前基于表的图像定位在IE11中有问题(最大高度在显示中不起作用:表元素)。我已经用基于内联的定位替换了它,它不仅在IE7和IE11中都很好用,而且需要更少的代码。


Here is my take on the subject. It'll only work if the container has specified size (max-width and max-height don't seem to get along with containers that don't have concrete size), but I wrote the css in a way that allows it to be reused (add picture-frame class and px125 size class to your existing container).

这是我对这个问题的看法。只有当容器具有指定的大小(最大宽度和最大高度似乎不能与没有具体大小的容器共存)时,它才会工作,但是我以允许重用它的方式编写css(在现有容器中添加picture-frame类和px125 size类)。

In css:

在css中:

.picture-frame{    vertical-align:top;    display:inline-block;    text-align:center;}.picture-frame.px125{    width:125px;    height:125px;    line-height:125px;}.picture-frame img{    margin-top:-4px; /* inline images have a slight offset for some reason when positioned using vertical-align */    max-width:100%;    max-height:100%;    display:inline-block;    vertical-align: middle;    border:0; /* Remove border on imgs enclosed in anchors in IE */}

And in html:

在html中:

<a href="#" class="picture-frame px125">    <img src="http://i.imgur.com/lesa2wS.png"/></a>

DEMO

/* Main style */.picture-frame{    vertical-align:top;    display:inline-block;    text-align:center;}.picture-frame.px32{    width:32px;    height:32px;    line-height:32px;}.picture-frame.px125{    width:125px;    height:125px;    line-height:125px;}.picture-frame img{    margin-top:-4px; /* inline images have a slight offset for some reason when positioned using vertical-align */    max-width:100%;    max-height:100%;    display:inline-block;    vertical-align: middle;    border:0; /* Remove border on imgs enclosed in anchors in IE */}/* Extras */.picture-frame{    padding: 5px;}.frame{    border:1px solid black;}
<p>32px</p><a href="#" class="picture-frame px32 frame">    <img src="http://i.imgur.com/lesa2wS.png"/></a><a href="#" class="picture-frame px32 frame">    <img src="http://i.imgur.com/kFMJxdZ.png"/></a><a href="#" class="picture-frame px32 frame">    <img src="http://i.imgur.com/BDabZj0.png"/></a><p>125px</p><a href="#" class="picture-frame px125 frame">    <img src="http://i.imgur.com/lesa2wS.png"/></a><a href="#" class="picture-frame px125 frame">    <img src="http://i.imgur.com/kFMJxdZ.png"/></a><a href="#" class="picture-frame px125 frame">    <img src="http://i.imgur.com/BDabZj0.png"/></a>


Edit: Possible further improvement using JS (upscaling images):

编辑:使用JS(放大图像)可能进一步改进:

function fixImage(img){    var $this = $(img);    var parent = $this.closest('.picture-frame');    if ($this.width() == parent.width() || $this.height() == parent.height())        return;    if ($this.width() > $this.height())        $this.css('width', parent.width() + 'px');    else        $this.css('height', parent.height() + 'px');}$('.picture-frame img:visible').each(function{    if (this.complete)        fixImage(this);    else        this.onload = function(){ fixImage(this) };});

#19


2  

A simple solution ( 4-step fix !!) that seem to work for me , is below. Hope it helps.The example uses the width to determine the overall size, but you can also flip it to use the height instead.

下面是一个简单的解决方案(4步修复!)希望它可以帮助。这个示例使用宽度来确定总体大小,但是您也可以翻转它来使用高度。

  1. Apply CSS styling to the image container ( eg
  2. 将CSS样式应用到图像容器(例如
  3. set the width property to the dimension you want
    • for dimensions use % for relative size,or autoscaling ( based on image container or display ) -use px ( or other ) for a static, or set dimension
    • 对于尺寸,使用%表示相对大小,或自动缩放(基于图像容器或显示)-使用px(或其他)表示静态尺寸或设置尺寸
  4. 将width属性设置为您想要的维度,使用%来表示相对大小,或自动缩放(基于图像容器或显示)—使用px(或其他)来表示静态维度或设置维度
  5. set the height property to automatically adjust, based on the width
  6. 设置高度属性,根据宽度自动调整
  7. ENJOY!
  8. 享受吧!

for example

例如

<img style="width:100%; height:auto;"                            src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"                />

#20


2  

As answered here, you can also use vh units instead of max-height: 100% if it doesn't work on your browser (like Chrome):

正如这里所回答的,您也可以使用vh单元而不是max-height: 100%如果它不能在您的浏览器上工作(如Chrome):

img {    max-height: 75vh;}

#21


1  

All the provided answers, including the accepted one, work only under the assumption that the div wrapper is of a fixed size. So this is how to do it whatever the size of the div wrapper is and this is very useful if you develop a responsive page:

所有提供的答案(包括已接受的答案)只能在假设div包装器是固定大小的情况下工作。这就是如何处理div包装器的大小这是非常有用的如果你开发一个响应式页面:

Write these declarations inside your DIV selector:

在您的DIV选择器中写入以下声明:

width : 8.33% /* or whatever percentage you want your div to take*/max-height : anyValueYouWant /*(in px or %)*/ 

Then put these declarations inside your IMG selector:

然后将这些声明放在IMG选择器中:

width : "100%" /* obligatory */max-height :  anyValueYouWant /*(in px or %)*/ 

VERY IMPORTANT:

非常重要:

The value of maxHeight must be the same for both the DIV and IMG selectors.

对于DIV和IMG选择器,maxHeight的值必须相同。

#22


0  

The solution is easy with a bit of maths...

解决方法很简单,只需一点数学知识……

Just put the image in a div and then in the html file where you specify the image set the width and height values in percentages using the pixel values of the image to calculate the exact ratio of width to height.

只需将图像放在div中,然后在html文件中指定图像,使用图像的像素值以百分比设置宽度和高度值,计算宽度和高度的精确比值。

For example, say you have an image that has a width of 200 pixels and a height of 160 pixels. You can safely say that the width value will be 100% because it is the larger value. To then calculate the height value you simply divide the height by the width which gives the percentage value of 80%. In the code it will look something like this...

例如,假设有一个图像宽度为200像素,高度为160像素。您可以放心地说宽度值将为100%,因为它是较大的值。要计算高度值,只需将高度除以宽度,宽度为80%。代码是这样的……

#23


0  

check my ans https://*.com/a/36712112/2439715

检查我的ans https://*.com/a/36712112/2439715

img{    width: 100%;    max-width: 800px;}

#24


0  

A simple solution is to use flex-box. Define the container's CSS to:

一个简单的解决方案是使用浮动框。将容器的CSS定义为:

.container{    display: flex;    justify-content: center;    align-items: center;    align-content: center;    overflow: hidden;    /*any custom height*/}

Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved. Cheers.

将所包含的图像宽度调整为100%,您应该在容器中得到一个以保存的尺寸为中心的图像。欢呼。

#25


-1  

Simplest way to do this is

最简单的方法是

by using object-fit

通过使用object-fit

<div class="container">  <img src="path/to/image.jpg"></div>.container{   height: 300px;}.container img{  height:100%;  width:100%;  object-fit: cover;}

If your using bootstrap just add the img-responsive class and changed to

如果您使用的是bootstrap,那么只需添加响应img的类并将其更改为

.container img{      object-fit: cover;    }

#26


-1  

Or you can simply use:

或者你可以简单地使用:

background-position:center;background-size:cover;

Now the image will take all the space of the div.

现在图像将占用div的所有空间。

#27


-1  

The following works perfectly for me:

以下是最适合我的:

img{   height: 99999px;   object-fit:contain;   max-height: 100%;   max-width: 100%;       display: block;   margin: auto auto;}

#28


-5  

Define div simply

定义div简单

   div.headerimg1 {       position: absolute;       top: 290px;       left: 81px;       width: 389px;            height: 349px;}<div class="headerimg1"><img src="" style="max-height:100%;height:auto;width:100%;max-width:100%;margin:auto;display:inline;"></div>