如何自动调整图像大小以适合“div”容器?

时间:2010-06-12 17:00:37

标签: html css image autoresize

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


示例:stackoverflow.com - 当图像插入编辑器面板并且图像太大而无法放到页面上时,图像会自动调整大小。

37 个答案:

答案 0 :(得分:1647)

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

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

此外,如果您只想指定宽度,请height: auto;

示例: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>

答案 1 :(得分:317)

object-fit

事实证明还有另一种方法可以做到这一点。

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

将完成这项工作。这是CSS 3的东西。

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

答案 2 :(得分:96)

目前无法以确定的方式正确执行此操作,使用固定大小的图像(如JPEG或PNG文件)。

要按比例调整图片大小,您必须将 的高度或宽度设置为“100%”,而不是两者都设置。如果将两者都设置为“100%” “,你的形象会被拉长。

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

  1. 如果您的图像和容器都是“纵向形状”或两者都是“横向形状”(分别高于它们的宽度,或者比它们的高度宽),那么高度或宽度中的哪一个都无关紧要%100" 。
  2. 如果您的图片是纵向图片,并且您的容器是横向图片,则必须在图片上设置height="100%"
  3. 如果您的图片是横向图片,而您的容器是纵向图片,则必须在图片上设置width="100%"
  4. 如果您的图像是SVG,这是一种可变大小的矢量图像格式,您可以使扩展适合容器自动发生。

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

    height
    width
    viewbox
    

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

答案 3 :(得分:68)

这是一个解决方案,即使提供的图像太小或太大而无法放入div,也可以在div中垂直和水平对齐img而不进行任何拉伸。

HTML内容:

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

CSS内容:

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

jQuery部分:

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

答案 4 :(得分:40)

简单一点!

为容器添加已修复 height,然后为其中的img标记设置widthmax-height

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

区别在于您将width设置为100%,而不是max-width

答案 5 :(得分:25)

美丽的黑客。

您有两种方法可以使图像响应。

  
      
  1. 当图像是背景图像时。
  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>

运行here

<小时/> 但是,在 SEO 方面,应该使用img标记来放置图像,因为它可以在{{>> 方面优于background-image,因为您可以在{{}中编写关键字 1 {} alt标记。所以这里你可以使图像响应。

  
      
  1. 当图片位于img标记内时。
  2.   
img

运行here

答案 6 :(得分:21)

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

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

鉴于此类HTML:

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

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 :(得分:20)

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

background-size: cover;

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

答案 8 :(得分:9)

此解决方案不会拉伸图像并填充整个容器,但会切割部分图像。

HTML:

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

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}

答案 9 :(得分:9)

我刚刚发布了一个jQuery插件,可以通过很多选项完全满足您的需求:

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

用法:

HTML

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

的JavaScript

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

答案 10 :(得分:7)

以下对我来说非常适合:

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

答案 11 :(得分:6)

我有更好的解决方案,无需任何JavaScript。它完全响应,我经常使用它。您经常需要将具有任何宽高比的图像拟合到具有指定宽高比的容器元素。并且让整个事情完全响应是必须的。

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

您可以单独设置最大宽度和最大高度;图像将尊重最小的图像(取决于图像的值和纵横比)。您还可以根据需要将图像设置为对齐(例如,对于无限白色背景上的产品图片,您可以轻松地将其定位到中心底部。)

答案 12 :(得分:5)

以下代码改编自之前的答案,并由我使用名为storm.jpg的图片进行测试。

这是显示图片的简单页面的完整HTML代码。这很完美,我和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>

答案 13 :(得分:5)

您必须告诉浏览器您放置它的位置的高度:

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

答案 14 :(得分:4)

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

答案 15 :(得分:4)

编辑:以前基于表格的图像定位在Internet Explorer 11中存在问题(max-heightdisplay:table元素中不起作用)。我用基于内联的定位替换它,它不仅在Internet Explorer 7和Internet Explorer 11中都能正常工作,而且还需要更少的代码。


这是我对这个问题的看法。只有当容器具有指定的大小(max-widthmax-height似乎与没有具体大小的容器相处时)它才会起作用,但我在一个容器中写了CSS内容允许重复使用的方法(将picture-frame类和px125大小类添加到现有容器中。

在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 images enclosed in anchors in Internet Explorer */
}

在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 images enclosed in anchors in Internet Explorer */
}

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


编辑:使用JavaScript(升级图像)可能进一步改进:

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) };
});

答案 16 :(得分:4)

我通过这种方式在水平和垂直方向上按比例缩放并按比例缩放图像:

#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;
}

在Internet Explorer,Firefox和Safari中进行了测试。

有关居中的更多信息是here

答案 17 :(得分:4)

图片太小时,

The accepted answer from Thorn007无法正常工作。

为了解决这个问题,我添加了比例因子。这样,它会使图像变大并填充div容器。

示例:

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

注意:

  1. 对于WebKit,您必须在样式中添加-webkit-transform:scale(4); -webkit-transform-origin:left top;
  2. 如果比例因子为4,则max-width = 400/4 = 100且max-height = 200/4 = 50
  3. 另一种解决方案是将最大宽度和最大高度设置为25%。它甚至更简单。

答案 18 :(得分:4)

将图片所需的高度和宽度提供给包含&lt; img&gt;的div。标签。不要忘记在正确的样式标签中给出高度/宽度。

在&lt; img&gt;中标记,将max-heightmax-width设为100%。

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

正确完成后,您可以在相应的课程中添加详细信息。

答案 19 :(得分:2)

一个似乎对我有用的简单解决方案(4步修复!!)如下所示。该示例使用宽度来确定整体大小,但您也可以将其翻转以使用高度。

  1. 将CSS样式应用于图像容器(例如,&lt; img&gt;)
  2. 将width属性设置为所需的维度
    • 对于尺寸,请使用%表示相对尺寸,或使用自动缩放(基于图像容器或显示)
    • px(或其他)用于静态或设置维度
  3. 根据宽度
  4. 将height属性设置为自动调整
  5. 享受!
  6. 例如,

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

答案 20 :(得分:2)

作为answered here,如果您的浏览器(例如Chrome)无效,您还可以使用vh单位而不是max-height: 100%

img {
    max-height: 75vh;
}

答案 21 :(得分:2)

假设div包装器具有固定大小,所有提供的答案(包括已接受的答案)仅 。这就是如何做到无论 div包装器的大小,如果您开发一个响应式页面,这非常有用:

DIV 选择器中写下这些声明:

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

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

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

非常重要:

maxHeight DIV IMG值必须相同选择器。

答案 22 :(得分:1)

有几种方法可以使图像适合<div>

img {
    object-fit: cover;
}

CSS object-fit 属性用于指定 <img><video> 应如何调整大小以适合其容器。

该属性告诉内容以多种方式填充容器;例如“保持纵横比”或“拉伸并占用尽可能多的空间”。

  • fill - 这是默认设置。图像被调整大小以填充给定的尺寸。如有必要,图像将被拉伸或压扁以适合
  • 包含 - 图像保持其纵横比,但调整大小以适应给定的尺寸
  • cover - 图像保持其纵横比并填充给定的尺寸。图像将被剪裁以适合
  • none - 不调整图像大小
  • 缩小 - 图像缩小到最小版本的无或包含

您可以找到更多工作示例 here

答案 23 :(得分:1)

如果您使用的是Bootstrap,则只需将img-responsive类添加到img标记中:

<img class="img-responsive" src="img_chania.jpg" alt="Chania">

Bootstrap Images

答案 24 :(得分:1)

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

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

将包含的图像宽度调整为100%,您应该在保留尺寸的容器中获得一个漂亮的居中图像。

答案 25 :(得分:1)

我使用以下代码解决了此问题:

<div class="container"><img src="image_url" /></div>
.container {
    height: 75px;
    width: 75px;
}

.container img {
    object-fit: cover;
    object-position: top;
    display: block;
    height: 100%;
    width: 100%;
}

答案 26 :(得分:0)

通过一些数学解决方案很容易......

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

例如,假设您的图像宽度为200像素,高度为160像素。您可以有把握地说宽度值将是100%,因为它是更大的值。然后计算高度值,您只需将高度除以宽度,即给出百分比值80%。在代码中它看起来像这样......

<div class="image_holder_div">
    <img src="some_pic.png" width="100%" height="80%">
</div>

答案 27 :(得分:0)

我看到很多人都建议适合对象,这是一个不错的选择。但是,如果您想同时在旧版浏览器中工作,则还有另一种方法可以轻松实现。

请在此处签出我的答案: IE and Edge fix for object-fit: cover;

非常简单。我采取的方法是使用绝对将图像放置在容器内,然后使用以下组合将其放置在中心位置

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

一旦它居中,我就给图片

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

这使图像获得Object-fit:cover的效果。


这里是上述逻辑的演示。

https://jsfiddle.net/furqan_694/s3xLe1gp/

此逻辑适用于所有浏览器。

答案 28 :(得分:0)

正如在我的 2014 Codepen example 中所见,我已经制定了一个解决方案,该解决方案可以在尽可能少的 javascript 的帮助下适用于任何未知的宽度/高度(纵横比)组合,以更改当容器的纵横比变化高于/低于图像纵横比时,图像如何居中的 CSS:

尝试通过拖动右下角来调整容器的大小:

// Detects when the window width is too narrow for the current image 
// aspect-ratio, and fits it to height 100% instead of width 100%.
const photo = document.images[0]

const onPhotoResize = new ResizeObserver(entries => 
  window.requestAnimationFrame(checkRatio)
)

onPhotoResize.observe(photo.parentNode)

function checkRatio(){
  const photoParent = photo.parentNode,
        imageAspectRatio = photo.clientWidth / photo.clientHeight,
        parentAspectRatio = photoParent.clientWidth / photoParent.clientHeight
        
  photo.classList[imageAspectRatio > parentAspectRatio ? 'add':'remove']('max')
}
.box{
  width: 20%;
  height: 60%;
  margin: auto;
  position: absolute;
  top:0; left:0; right:0; bottom:0;
  resize: both;
  overflow: hidden;
  border: 5px solid red;
 } 

.box > img{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    transform: translate(-50%, -50%); 
}

.box > img.max{ width:auto; height:100%; }
<div class='box'>
  <img src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg">
</div>

答案 29 :(得分:0)

这是我的解决方案。您需要将图片插入两次。但是它不使用js,并且img将调整为宽度和高度。您可以单击“运行代码片段 - 整页”,打开开发控制台并调整窗口宽度以查看响应效果。

    /* responsive width */
      .responsivewidth{
        background: lightsalmon;
        height: 100px;
        width: 50%;
      }
      /* Widthlimit */
      .maxedbywidth {
        background: navy;
        height: 200px;
        width: 100px;
      }
      .div1 {
        max-height: 100%;
        position: relative;
        box-sizing: content-box;

        /* Center: */
        top: 50%;
        transform: translateY(-50%);
      }
      .margerimg {
        height: auto;
        max-width: 100%;
        opacity: 0;
      }
      .div2 {
        height: 100%;
        width: fit-content;
        position: absolute;
        top: 0;

        /* Center: */
        left: 50%;
        transform: translateX(-50%);
      }
      .mainimg {
        max-height: 100%;
        max-width: 100%;
      }
<div class="responsivewidth">
      <div class="div1">
        <img class="margerimg" src="https://via.placeholder.com/2000x1500" />
        <div class="div2">
          <img class="mainimg" src="https://via.placeholder.com/2000x1500" />
        </div>
      </div>
    </div>
    <div class="maxedbywidth">
      <div class="div1">
        <img class="margerimg" src="https://via.placeholder.com/2000x1500" />
        <div class="div2">
          <img class="mainimg" src="https://via.placeholder.com/2000x1500" />
        </div>
      </div>
    </div>

答案 30 :(得分:-1)

最简单的方法是使用object-fit

<div class="container">
  <img src="path/to/image.jpg">
</div>

.container{
   height: 300px;
}

.container img{
  height: 100%;
  width: 100%;
  object-fit: cover;
}

如果您使用的是Bootstrap,只需添加img-responsive类并更改为

即可
.container img{
    object-fit: cover;
}

答案 31 :(得分:-1)

检查我的回答 Make an image responsive - simplest way -

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

答案 32 :(得分:-1)

你用下面的类来解决这个问题;

.custom-image{height: auto; width: auto; max-height: 100%; max-width: 100%; object-fit: contain;}

答案 33 :(得分:-1)

这篇文章可能对您有所帮助:

  .square {
     position: relative;
     width: 300px;
     height: 300px;
     overflow: hidden;
  }
  img {
     position: absolute;
     max-width: 100%;
     width: 100%;
     height: auto;
     top: 50%;
     left: 50%;
     transform: translate( -50%, -50%);
 }
  img.landscape {
    height: 100%;
    width: auto;
}
<div class="square">
   <img src="https://unsplash.it/400/500" alt="Image" />
</div>
<div class="square">
   <img src="https://unsplash.it/500/400" class="landscape" alt="Image" />
</div>

Simple CSS Solutions: How to fit images with different dimensions in set containers (2017-05-01)

  .square {
     position: relative;
     width: 441px;
     height: 200px;
     overflow: hidden;
     border:1px solid black;
  }
  img {
     max-width: 100%;
/*     width: 100%;*/<----it stretch image and fit into the parent
     height: auto;
/*     transform: translate( -50%, -50%);*/<-----set vertically and horizontally center
 }
  img.landscape {
    height: 100%;
    width: auto;
}
<div class="square">
   <img src="https://cdn.pixabay.com/photo/2020/08/28/12/32/man-5524488__340.jpg" alt="Image" />
</div>

答案 34 :(得分:-1)

使用上一个答案中的 max-height: 100% 允许在窗口被从水平边缘拉出/扩展时根据包含窗口的大小调整来调整图像的大小。 从底部拉出,如果提起,将切片图像的可见性,而不是缩放图像。然后使用 max-height: 75vh; 允许缩放图像如果从底部而不是侧面将两者放在一起得到结果根据在两个方向上拉动的容器来缩放图像;

.myPics {
  max-height: 75vh;
  max-width: 100%;
}

或者你可以使用

.myPics {  
  width: 90%;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

答案 35 :(得分:-2)

或者你可以简单地使用:

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

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

答案 36 :(得分:-5)

将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>
相关问题