Html 如何创建比例图像高度/宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3380252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create proportional image height/width
提问by PizzaPie
So, I want to have an image resized to 30% of its original height/width. Pretend you don't know its height or width, how would you go about it using only CSS/HTML?
所以,我想将图像大小调整为其原始高度/宽度的 30%。假设您不知道它的高度或宽度,您将如何仅使用 CSS/HTML 来处理它?
回答by Blum
If you need a quick inline solution:
如果您需要快速的内联解决方案:
<img style="max-width: 100px; height: auto; " src="image.jpg" />
回答by Pat
Update:
更新:
Using a display: inline-block;
wrapper, it's possible to make this happen with CSS only.
使用display: inline-block;
包装器,可以仅使用 CSS 来实现这一点。
HTML
HTML
<div class="holder">
<img src="your-image.jpg" />
</div>
CSS
CSS
.holder {
width: auto;
display: inline-block;
}
.holder img {
width: 30%; /* Will shrink image to 30% of its original width */
height: auto;
}?
The wrapper collapses to the original width of the image, and then the width: 30%
CSS rule on the images causes the image to shrink down to 30% of its parent's width (which was its original width).
包装器折叠到图像的原始宽度,然后图像上的width: 30%
CSS 规则使图像缩小到其父级宽度(原始宽度)的 30%。
Here's a demo in action.
这是一个实际演示。
Sadly no pure HTML/CSS way to do it as neither is geared to perform calculations like that.However, it's pretty simple with a snippet of jQuery:
遗憾的是,没有纯 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);
}
});