【问题标题】:CSS/Javascript image size to fit while cropping and preserving aspect ratio裁剪和保留纵横比时适合的 CSS/Javascript 图像大小
【发布时间】:2014-03-15 23:32:24
【问题描述】:

我有一个大小为 180x270 的块,我需要显示图像

图像大小可以变化,我想确保它扩大或缩小,以便较小的边框(高度或宽度)与块相匹配,而较大的边框在保持纵横比的同时被裁剪。

示例如下: - 360x600 的图像被调整为 180x300,我将高度从 300 裁剪到 270 - 100x135 的图像被调整为 200x270,我将宽度从 200 裁剪为 180

基本上,我想确保在扩展/缩小图像时没有空白,同时通过裁剪超出块的部分来保持纵横比

对可以处理此问题的 css 或 javascripts 有什么建议吗?

【问题讨论】:

    标签: javascript html css image


    【解决方案1】:

    您似乎正在寻找background-size:cover,当图像是background-image 时,它可以工作

    background:url(imgurl.jpg) /* Other background image properties */;
    background-size:cover;
    

    Demo

    【讨论】:

      【解决方案2】:

      如果你可以使用 bg-image 来完成任务,Zach 的解决方案是最好的,但如果你需要使用 <img> 标签(有些情况是 advised),那么你需要 javascript 来计算图像的纵横比并确定它是否比目标帧更蹲或更垂直拉伸。然后还有一点 CSS:

      JavaScript

      //obtain a dom-reference for the image using getElementById
      //or by some other means depending on what you know of its HTML
      var img = document.getElementById('some-image-id') 
      
      
      var aspectRatio = img.clientWidth/img.clientHeight;
      
      //if the img is more squat, set it's height equal to the target frame's height
      if(aspectRatio > (270/180)){
          img.style.height = 180 //image is
      }
      //otherwise the image is more vertically stretched
      // so set the img width equal to the target frame's width
      else{
          img.style.width = 270;
      }
      

      这将设置

      CSS

      最后,让一个超大尺寸的图像在包装内垂直和水平居中,不管是如何匹配的:

      .wrapper{
          position:relative;
          display:inline-block; 
      }
      .wrapper img{
          position:absolute;
          top:-9999px;
          right:-9999px;
          bottom:-9999px;
          left:-9999px;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-02
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 2013-09-09
        • 2020-07-30
        相关资源
        最近更新 更多