如何在div wather图像大小中拟合图像最大然后div或min然后div

7 html css

如何在div中拟合图像?图像大小可以是最大,然后是div或min然后是div.

HTML代码

<div class="main">
  <img scr="image.jpg">
</div>
Run Code Online (Sandbox Code Playgroud)

CSS代码

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

img{
  // answer code
}
Run Code Online (Sandbox Code Playgroud)

如何设置图像css如下:

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

Sub*_*jit 16

您可以使用 :-

img { max-width: 100%; height: auto; } // This would help you to automatically fit the image.
Run Code Online (Sandbox Code Playgroud)

编辑:

上面的css代码可以帮助您处理大小大于div的图像.但是不适合小于div的图像.为实现目标需要一点JQuery,请在下面找到: -

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

当图像小于div时它会调整自身并根据您的要求适合div.

因此,将css和脚本放在两个条件下都可以使用.