如何创建比例图像高度/宽度

时间:2010-08-01 00:09:18

标签: html css image-resizing

所以,我希望将图像大小调整为其原始高度/宽度的30%。假装你不知道它的高度或宽度,你将如何仅使用CSS / HTML?

3 个答案:

答案 0 :(得分:35)

如果您需要快速内联解决方案:

<img style="max-width: 100px; height: auto; " src="image.jpg" />

答案 1 :(得分:27)

<强>更新

使用display: inline-block;包装器,可以仅使用CSS实现此目的。

<强> HTML

<div class="holder">
    <img src="your-image.jpg" />
</div>

<强> CSS

.holder {   
  width: auto;
  display: inline-block;    
}

.holder img {
  width: 30%; /* Will shrink image to 30% of its original width */
  height: auto;    
}​

包装器折叠到图像的原始宽度,然后图像上的width: 30% CSS规则使图像缩小到其父宽度的30%(这是其原始宽度)。

这是demo in action


可悲的是没有纯HTML / CSS方式来做这件事,因为它们都不适合执行那样的计算。但是,使用jQuery片段非常简单:

$('img.toResizeClass').each(function(){

    var $img = $(this),
        imgWidth = $img.width(),
        imgHeight = $img.height();

    if(imgWidth > imgHeight){
        $img.width(imgWidth * 0.3);
    } else {
        $img.height(imgHeight * 0.3);
    }
});

答案 2 :(得分:1)

<img style="max-width: 100%; height: auto; " src="image.jpg" />

我使用百分比到最大宽度,非常好