如何在div中保存图像(img)并保持宽高比? [英] How do I fit an image (img) inside a div and keep the aspect ratio?

查看:129
本文介绍了如何在div中保存图像(img)并保持宽高比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个48x48的div,里面有一个img元素,我想要适应它,而不会丢失任何部分,在平均时间比率保持,是可以使用html和css?

解决方案

如果你在写css时不知道图像的尺寸,你需要一些JavaScript来防止裁剪。



HTML& JavaScript



 < div id =container> 
< img src =something.jpgalt =/>
< / div>

< script type =text / javascript>
(function(){

var img = document.getElementById('container')。firstChild;
img.onload = function(){
if .height> img.width){
img.height ='100%';
img.width ='auto';
}
};

}());
< / script>



CSS



  #container {
width:48px;
height:48px;
}

#container img {
width:100%;
}

如果使用JavaScript库,您可能希望利用它。 / p>

I have a 48x48 div and inside it there is an img element, I want to fit it into the div without losing any part, in the mean time the ratio is kept, is it achievable using html and css?

解决方案

You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.

HTML & JavaScript

<div id="container">
    <img src="something.jpg" alt="" />
</div>

<script type="text/javascript">
(function() {

var img = document.getElementById('container').firstChild;
img.onload = function() {
    if(img.height > img.width) {
        img.height = '100%';
        img.width = 'auto';
    }
};

}());
</script>

CSS

#container {
   width: 48px;
   height: 48px;
}

#container img {
   width: 100%;
}

If you use a JavaScript Library you might want to take advantage of it.

这篇关于如何在div中保存图像(img)并保持宽高比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆