how to create proportional image height/width

后端 未结 2 1854
無奈伤痛
無奈伤痛 2020-12-13 20:12

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?

相关标签:
2条回答
  • 2020-12-13 20:47

    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);
        }
    });
    
    0 讨论(0)
  • 2020-12-13 21:01

    If you need a quick inline solution:

    <img style="max-width: 100px; height: auto; " src="image.jpg" />
    
    0 讨论(0)
提交回复
热议问题