9

如何在 div 中放置图像?图像大小可以是 max 然后 div 或 min 然后 div。

html代码

<div class="main">
  <img scr="image.jpg">
</div>

CSS 代码

.main{
  height:200px;
  width:200px;
}

img{
  // answer code
}

如何使用以下设置图像 css:

  1. 图像高度 100 和宽度 100
  2. 图像高度 300 和宽度 300
4

3 回答 3

19

您可以使用:

img { max-width: 100%; height: auto; } // This would help you to automatically fit the image.

上面的 css 代码将帮助您处理尺寸大于 div 的图像。但不适合小于 div 的图像。需要一些 jQuery 来实现您的目标,请在下面找到它:

$(document).ready(function(){
    imageWidth = $('.main img').width();
    parentWidth = $('.main').width();
    if (imageWidth > parentWidth) {
        $('.main img').css('width', '100%');
    }
});

当图像小于 div 时会发生什么情况,它会根据您的要求自行调整大小并适合 div。

因此,将 css 和脚本放置在这两种情况下。

于 2012-06-21T07:37:37.557 回答
1

在子元素“height:inherit;”中使用它 并且这个元素将是相同高度的伙伴。

.main{
       height:200px;
       width:200px;
}

.img{
  height: inherit; //the imagem will be heigth 200px automatic
}
于 2020-04-12T21:48:02.103 回答
-1

如果您的图像始终是正方形,则只需添加 img{ width: 200px; height: 200px; }

如果没有,那么

.main {
    width: 200px;
    height: 200px;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}
img {
    max-width: 200px;
    max-height: 200px;
    /* IE7 doesn't support display: table-cell property? so hack */
    *margin-top: expression((parentNode.offsetHeight.offsetHeight/2)-(parseInt(this.offsetHeight)/2) <0 ? "0" :(parentNode.offsetHeight/2)-(parseInt(this.offsetHeight)/2) +'px');     }

在这里查看http://jsfiddle.net/qBDT4/1/

于 2012-06-21T08:50:43.680 回答