如何在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如下:
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和脚本放在两个条件下都可以使用.