首頁  >  文章  >  web前端  >  如何使用 CSS 縮放圖像以適應邊界框,同時保持其縱橫比?

如何使用 CSS 縮放圖像以適應邊界框,同時保持其縱橫比?

Patricia Arquette
Patricia Arquette原創
2024-10-26 20:59:03549瀏覽

How can I scale an image to fit a bounding box while maintaining its aspect ratio using CSS?

使用CSS 縮放影像以適合邊界框

在影像大於其容器的情況下,CSS 使用max 提供了一個簡單的解決方案-width 和max-height 屬性。然而,當目標是放大圖像直到其某個尺寸填滿整個容器時,這種方法就不夠了。

CSS3 解

感謝CSS3,有一個可行的解決方案,利用background-image和background-size屬性:

  1. HTML:

    <code class="html"><div class="bounding-box">
    </div></code>
  2. CSS:

    <code class="css">.bounding-box {
      background-image: url(...);
      background-repeat: no-repeat;
      background-size: contain;
    }</code>

此方法可確保影像縮放以適合邊界框,同時保持其縱橫比。這裡測試一下:http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain。

對齊和相容性

對於支援CSS3的瀏覽器,此方法完全相容。要使div 居中,請使用以下變體:
<code class="css">.bounding-box {
  background-image: url(...);
  background-size: contain;
  position: absolute;
  background-position: center;
  background-repeat: no-repeat;
  height: 100%;
  width: 100%;
}</code>

透過利用背景大小屬性,CSS3 提供了一種方便有效的方法來縮放圖像以適合邊界框,保留圖像比例並允許靈活對齊選項。

以上是如何使用 CSS 縮放圖像以適應邊界框,同時保持其縱橫比?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn