簡體   English   中英

CSS強制圖像調整大小並保持縱橫比

[英]CSS force image resize and keep aspect ratio

我正在處理圖像,但遇到了縱橫比問題。

<img src="big_image.jpg" width="900" height="600" alt="" />

如您所見, heightwidth已經指定。 我為圖像添加了一個 CSS 規則:

img {
  max-width: 500px;
}

但是對於big_image.jpg ,我收到width=500height=600 如何設置要調整大小的圖像,同時保持其縱橫比。

 img { display: block; max-width:230px; max-height:95px; width: auto; height: auto; }
 <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p> <img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png">

如果指定區域太大,這將使圖像縮小(作為缺點,它不會放大圖像)。

我一直在努力解決這個問題,最終得出了這個簡單的解決方案:

object-fit: cover;
width: 100%;
height: 250px;

您可以調整寬度和高度以滿足您的需要,並且 object-fit 屬性將為您進行裁剪。

有關object-fit屬性的可能值和兼容性表的更多信息,請訪問: https : //developer.mozilla.org/en-US/docs/Web/CSS/object-fit

干杯。

下面的解決方案將允許放大和縮小圖像,具體取決於父框的寬度。

所有圖像都有一個固定寬度的父容器,僅用於演示目的 在生產中,這將是父框的寬度。

最佳實踐(2018 年):

此解決方案告訴瀏覽器以最大可用寬度呈現圖像,並將高度調整為該寬度的百分比。

 .parent { width: 100px; } img { display: block; width: 100%; height: auto; }
 <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p> <div class="parent"> <img width="400" height="400" src="https://placehold.it/400x400"> </div>

更高級的解決方案:

使用更高級的解決方案,您將能夠裁剪圖像而不管其大小並添加背景顏色以補償裁剪。

 .parent { width: 100px; } .container { display: block; width: 100%; height: auto; position: relative; overflow: hidden; padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */ } .container img { display: block; max-width: 100%; max-height: 100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
 <p>This image is originally 640x220, but should get resized by the CSS:</p> <div class="parent"> <div class="container"> <img width="640" height="220" src="https://placehold.it/640x220"> </div> </div>

對於指定padding的行,需要計算圖片的縱橫比,例如:

640px (w) = 100%
220px (h) = ?

640/220 = 2.909
100/2.909 = 34.37%

因此,頂部填充 = 34.37%。

background-size 屬性僅為 ie>=9,但如果您覺得合適,您可以使用帶有background-image的 div 並設置background-size: contain

div.image{
    background-image: url("your/url/here");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

現在,您可以將 div 大小設置為您想要的任何大小,不僅圖像將保持其縱橫比,它還將在 div 內垂直和水平集中。 只是不要忘記在 css 上設置大小,因為 div 在標簽本身上沒有寬度/高度屬性。

這種方法不同於 setecs 答案,使用它圖像區域將是恆定的並由您定義(根據 div 大小和圖像縱橫比水平或垂直留下空白空間),而 setecs 答案將為您提供一個框縮放圖像的大小(沒有空格)。

編輯:根據MDN 背景大小文檔,您可以使用專有過濾器聲明模擬 IE8 中的背景大小屬性:

盡管 Internet Explorer 8 不支持 background-size 屬性,但可以使用非標准的 -ms-filter 函數來模擬其某些功能:

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";

與這里的一些答案非常相似,但就我而言,我的圖像有時更高,有時更大。

這種風格就像一種魅力,可以確保所有圖像都使用所有可用空間,保持比例而不是剪切:

.img {
   object-fit: contain;
   max-width: 100%;
   max-height: 100%;
   width: auto;
   height: auto;
}

刪除“高度”屬性。

<img src="big_image.jpg" width="900" alt=""/>

通過指定兩者,您正在更改圖像的縱橫比。 只需設置一個將調整大小但保留縱橫比。

(可選)限制尺寸過大:

<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>

Firefox 71+ (2019-12-03) 和Chrome 79+ (2019-12-10) 支持將IMG元素的widthheight HTML 屬性內部映射到新的aspect-ratio CSS 屬性(該屬性本身尚未可直接使用)。

計算出的縱橫比用於為圖片預留空間,直到加載完畢,只要計算出的縱橫比與圖片的實際縱橫比相等,就可以防止圖片加載后頁面“跳轉”。

為此,必須通過 CSS 將兩個圖像尺寸之一覆蓋為auto值:

IMG {max-width: 100%; height: auto; }
<img src="example.png" width="1280" height="720" alt="Example" />

在該示例中,即使圖像尚未加載並且由於max-width: 100%導致有效圖像寬度小於 1280,也會保持 16:9 (1280:720) 的縱橫比。

另請參閱相關的 Firefox錯誤 392261

這是一個解決方案:

img {
   width: 100%;
   height: auto;
   object-fit: cover;
}

這將確保圖像始終覆蓋整個父級(縮小和放大)並保持相同的縱橫比。

只需將其添加到您的 css 中,它會在保持原始比例的情況下自動縮小和擴展。

img {
    display: block;
    max-width: 100%;
    max-height: 100%;
    width: auto;
    height: auto;
}

將圖像容器標簽的 CSS 類設置為image-class

<div class="image-full"></div>

並將其添加到您的 CSS 樣式表中。

.image-full {
    background: url(...some image...) no-repeat;
    background-size: cover;
    background-position: center center;
}

要在仍然強制圖像具有特定縱橫比的同時保持響應圖像,您可以執行以下操作:

HTML:

<div class="ratio2-1">
   <img src="../image.png" alt="image">
</div>

和 SCSS:

.ratio2-1 {
  overflow: hidden;
  position: relative;

  &:before {
    content: '';
    display: block;
    padding-top: 50%; // ratio 2:1
  }

  img {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
  }
}

無論作者上傳的圖像大小如何,這都可用於強制執行特定的縱橫比。

感謝http://codepen.io/Kseso/pen/bfdhg上的 @Kseso。 檢查此 URL 以獲取更多比率和工作示例。

要強制適合精確尺寸的圖像,您不需要編寫太多代碼。 太簡單了

 img{ width: 200px; height: auto; object-fit: contain; /* Fit logo in the image size */ -o-object-fit: contain; /* Fit logo fro opera browser */ object-position: top; /* Set logo position */ -o-object-position: top; /* Logo position for opera browser */ }
 <img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">

https://jsfiddle.net/sot2qgj6/3/

如果您想放置具有固定寬度百分比不是固定像素寬度的圖像,這就是答案。

這在處理不同尺寸的屏幕時會很有用。

訣竅是

  1. 使用padding-top從寬度設置高度。
  2. 使用position: absolute將圖像放入填充空間。
  3. 使用max-height and max-width確保圖像不會覆蓋父元素。
  4. 使用display:block and margin: auto使圖像居中。

我還評論了小提琴中的大部分技巧。


我還找到了一些其他方法來實現這一點。 html 中將沒有真實圖像,因此當我需要 html 中的“img”元素時,我個人更喜歡最佳答案。

使用背景http://jsfiddle.net/4660s79h/2/ 的簡單 css

背景圖片,頂部帶有文字http://jsfiddle.net/4660s79h/1/

使用絕對位置的概念來自這里http://www.w3schools.com/howto/howto_css_aspect_ratio.asp

我建議采用響應式方法,最佳實踐是使用Viewport 單位和 min/max 屬性,如下所示:

img{
  display: block;
  width: 12vw;
  height:12vw;
  max-width:100%;
  min-width:100px;
  min-height:100px;
  object-fit:contain;
}

這是精神上的。 使用 scale-down 屬性 - 它會自我解釋。

內聯樣式:

<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />

這將阻止 flex 拉伸它。 在這種情況下,圖像將變為其父容器寬度的 50%,高度將縮小以匹配。

把事情簡單化。

你可以使用這個:

img { 
    width: 500px; 
    height: 600px; 
    object-fit: contain; 
    position: relative; 
    top: 50%; 
    transform: translateY(-50%); 
}

您可以像這樣創建一個 div:

<div class="image" style="background-image:url('/to/your/image')"></div>

並使用此 css 對其進行樣式設置:

height: 100%;
width: 100%;
background-position: center center;
background-repeat: no-repeat;
background-size: contain; // this can also be cover

如果指定區域太大,這將使圖像縮小(作為缺點,它不會放大圖像)。

setec 的解決方案適用於自動模式下的“縮小以適應”。 但是,為了最佳地擴展以適應“自動”模式,您需要首先將接收到的圖像放入臨時 ID,檢查它是否可以在高度或寬度上擴展(取決於其縱橫比 v/s您的顯示塊),

$(".temp_image").attr("src","str.jpg" ).load(function() { 
    // callback to get actual size of received image 

    // define to expand image in Height 
    if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
        $(".image").css('height', max_height_of_box);
        $(".image").css('width',' auto');
    } else { 
        // define to expand image in Width
        $(".image").css('width' ,max_width_of_box);
        $(".image").css('height','auto');
    }
    //Finally put the image to Completely Fill the display area while maintaining aspect ratio.
    $(".image").attr("src","str.jpg");
});

當接收到的圖像小於顯示框時,這種方法很有用。 您必須將它們以原始小尺寸而不是它們的擴展版本保存在您的服務器上,以填充您的更大顯示框以節省尺寸和帶寬。

您可以將容器設置為display: flexalign-items: center (其他align-items值也適用)。 除了align-items您還可以在圖像本身上設置align-self

您可以使用aspect-ratio屬性 css

.my-image {
 aspect-ratio: 1/1; // square
 aspect-ratio: 16/9; // wide screen 1080p
 aspect-ratio: 4/3;
 aspect-ratio: 2/3;
}

 img { max-width: 80px; /* Also works with percentage value like 100% */ height: auto; }
 <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p> <img width="400" height="400" src="https://i.stack.imgur.com/aEEkn.png"> <p>Let's say the author of the HTML deliberately wants the height to be half the value of the width, this CSS will ignore the HTML author's wishes, which may or may not be what you want: </p> <img width="400" height="200" src="https://i.stack.imgur.com/aEEkn.png">

如何使用偽元素進行垂直對齊? 這個較少的代碼用於輪播,但我想它適用於每個固定大小的容器。 它將保持縱橫比並在頂部/底部或左側/寫入最短尺寸的地方插入@gray-dark 條。 同時,圖像由 text-align 水平居中,由偽元素垂直居中。

    > li {
      float: left;
      overflow: hidden;
      background-color: @gray-dark;
      text-align: center;

      > a img,
      > img {
        display: inline-block;
        max-height: 100%;
        max-width: 100%;
        width: auto;
        height: auto;
        margin: auto;
        text-align: center;
      }

      // Add pseudo element for vertical alignment of inline (img)
      &:before {
        content: "";
        height: 100%;
        display: inline-block;
        vertical-align: middle;
      }
    }

全屏演示:

img[data-attribute] {height: 100vh;}

請記住,如果視口高度大於圖像,圖像自然會相對於差異降級。

如果應用程序可以具有任何縱橫比或分辨率的圖像,那么您可以按照此鏈接管理高度和寬度。

這使用 Javascript 和 HTML

https://stackoverflow.com/a/65090175/13338731

您可以使用:-

transform: scaleX(1.2);

改變寬度而不改變高度。

transform: scaleY(1.2);

在不改變寬度的情況下改變高度

您可以在 html 和 css 中的圖像和視頻標簽上使用它。 這也不會改變縱橫比。

只需用aspect-ratio屬性替換height屬性。

 img { max-width: 500px; aspect-ratio: 900 / 600; }
 <img src="big_image.png" width="900"/>

aspect-ratio屬性不是必需的,但可以防止圖像布局偏移。

我認為,最后這是最好的解決方案,簡單易行

img {
    display: block;
    max-width: 100%;
    max-height: 100%;
    width: auto;
    height: auto;
}

暫無
暫無

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

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