【问题标题】:how to create proportional image height/width如何创建比例图像高度/宽度
【发布时间】:2010-08-01 00:09:17
【问题描述】:

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

【问题讨论】:

    标签: html css image-resizing


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      更新:

      使用 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 的 sn-p 非常简单:

      $('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);
          }
      });
      

      【讨论】:

      • 好主意,但不是“仅使用 CSS/HTML”,有人有这个解决方案吗?
      • @AbishaiGray 想出了一个 CSS 唯一的方法来实现宽度。
      【解决方案3】:
      <img style="max-width: 100%; height: auto; " src="image.jpg" />
      

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

      【讨论】:

        猜你喜欢
        • 2021-10-25
        • 2020-07-15
        • 2010-11-08
        • 2022-08-19
        • 1970-01-01
        • 2013-04-07
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        相关资源
        最近更新 更多