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

发布于 2024-09-12 03:59:46 字数 71 浏览 0 评论 0原文

因此,我希望将图像大小调整为其原始高度/宽度的 30%。假设您不知道它的高度或宽度,您将如何仅使用 CSS/HTML 来实现它?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你是年少的欢喜 2024-09-19 03:59:49

更新:

使用 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%。

这是实际演示


遗憾的是没有纯 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);
    }
});

Update:

Using a display: inline-block; wrapper, it's possible to make this happen with CSS only.

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;    
}​

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).

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:

$('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);
    }
});
ゝ偶尔ゞ 2024-09-19 03:59:49
<img style="max-width: 100%; height: auto; " src="image.jpg" />

我正在使用最大宽度的百分比,非常好

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

i am using percent to max-width and very nice

最美不过初阳 2024-09-19 03:59:48

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

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

If you need a quick inline solution:

<img style="max-width: 100px; height: auto; " src="image.jpg" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文