簡體   English   中英

保持縱橫比與最小/最大高度/寬度?

[英]Maintaining aspect ratio with min/max height/width?

我的網站上有一個用戶可以上傳圖片的圖庫。

我希望圖像位於保持其高度的div中,圖像的高度不應超過500px。 寬度應自動保持縱橫比。

HTML:

<div id="gallery">
    <img src="uploads/my-dynamic-img.jpg">
</div>

我試過這個CSS:

#gallery{
    height: 500px;

    img{
        max-height: 500px;
        max-width: 100%;
    }
}

以上效果很好,畫廊總是500px高,圖像高度不超過500px。 我遇到問題雖然圖像較小,但如果用戶上傳的圖片非常小,我希望它“炸毀”至少200px。 我知道這可以通過在圖像上設置min-height來實現,問題是,如果圖像高度小於200像素但是寬度為2000像素,則圖像的高度會高達200像素,但是縱橫比被擰緊,因為圖像比圖像父div更寬。

我怎樣才能達到最小高度但保持縱橫比?

您正在尋找的屬性是object-fit 這是Opera的創新之一,您可以在2011年關於對象適配的開發文章中閱讀更多關於它的內容 (是的,它已經存在了很長時間)。 幾年前,我無法向你推薦它,但是caniuse表明其他人都開始追趕:

  • Opera 10.6-12.1(-o-前綴)
  • Chrome 31+
  • 歌劇院19+
  • Safari 7.1+
  • iOS 8+
  • Android 4.4+

http://caniuse.com/#search=object-fit

#gallery img {
    -o-object-fit: contain;
    object-fit: contain;
}

使用contain值將強制圖像保持其縱橫比,無論如何。

或者,您可能希望使用此代碼:

#gallery img {
    -o-object-fit: cover;
    object-fit: cover;
    overflow: hidden;
}

http://sassmeister.com/gist/9b130efdae95bfa4338e

我知道可能實現此目的的唯一方法是將widthheightauto

#gallery{
    height: 500px;

    img{
        max-height: 500px;
        width: auto;
    }
}

我不知道這是否只能使用CSS。

但是,您可以使用幾行JavaScript完成相同的操作:

var img= document.querySelectorAll('img');
for(var i = 0 ; i < img.length ; i++) {
  img[i].onload= function() {
    var h= this.naturalHeight;
    h= Math.min(500,Math.max(200,h));
    this.style.height= h+'px';
  }
}

這會將所有圖像的高度設置為200px到500px之間。 寬度將自動縮放。

 var img= document.querySelectorAll('img'); for(var i = 0 ; i < img.length ; i++) { img[i].onload= function() { var h= this.naturalHeight; h= Math.min(500,Math.max(200,h)); } } 
 #gallery{ height: 500px; width: 400px; overflow: hidden; } 
 <div id="gallery"> <img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png"> </div> 

實際上,我一直想做類似的事情。 如果你是這樣的話,jQuery中有些東西。

SCSS:

#gallery {
  height: 500px;

  img {
    max-height: 100%;
  }

  .small {
    width: 100%;
    max-width: 500px;
    height: auto;
  }

  .regular {
    width: auto;
    min-height: 200px;
  }
}

jQuery的:

$( 'img' ).each( function() {

  var imageWidth = parseFloat( $( this ).css( 'width' ) );
  var imageHeight = parseFloat( $( this ).css( 'height' ) );

  if( imageHeight <= 200 && imageWidth >= 200 ) {
    $( this ).addClass( 'small' );
  }
  else {
    $( this ).addClass( 'regular' );
  }
});

CodePen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM