使用 CSS 按比例調整影像大小


為了使應用程式具有響應式設計,我們還需要使影像具有響應性。如果影像沒有響應性,應用程式中就會出現溢位,看起來很糟糕。

因此,我們還需要根據父元素的尺寸按比例增加或減少影像的尺寸。在這裡,我們將學習使用 CSS 按比例調整影像大小的各種方法。

語法

使用者可以按照以下語法使用“width” CSS 屬性按比例調整影像大小。

img {
   width: 100%;
   height: auto;
}

在上面的語法中,我們為影像設定了 100% 的寬度和自動高度,使其具有響應性。

示例

在下面的示例中,我們建立了 div 元素,賦予它“image”類名,並在 div 元素內添加了一個影像作為子元素。

在 CSS 中,我們以百分比設定了 div 元素的寬度,等於總寬度的 30%。此外,我們為影像設定了 100% 的寬度和自動高度。使用者可以更改螢幕尺寸,並觀察到影像大小會根據螢幕尺寸按比例減小和增大。

<html>
<head>
   <style>
      .image {
         width: 30%;
         margin: 0 auto;
         border: 3px solid red;
         padding: 10px;
      }
      img {
         width: 100%;
         height: auto;
      }
   </style>
</head>
<body>
   <h2> Using the <i> width CSS property </i> to resize image proportionally </h2>
   <div class = "image">
      <img src = "https://tutorialspoint.tw/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

示例

在下面的示例中,我們使用了“object-fit: contain” CSS 屬性來按比例減小影像的大小。在這裡,我們為影像的父 div 元素設定了比例寬度。此外,我們還為“img”元素使用了“object-fit: contain” CSS 屬性。在輸出中,使用者可以觀察到影像具有響應性,其尺寸會根據 div 元素的尺寸變化。

<html>
<head>
   <style>
      .image {
         width: 30%;
         margin: 0 auto;
         border: 3px solid red;
         padding: 10px;
      }
      img {
         width: 100%;
         height: 50%;
         object-fit: contain;
      }
   </style>
</head>
<body>
   <h3> Using the <i> object-fit: contain CSS property </i> to resize image proportionally </h3>
   <div class = "image">
      <img src = "https://tutorialspoint.tw/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

示例

在下面的示例中,我們使用了“background-size” CSS 屬性來按比例更改影像的尺寸。在這裡,我們為 div 元素設定了背景影像。此外,我們還使用了“contain”作為“background-size” CSS 屬性的值。它將影像擴充套件到整個 div。如果 div 元素的尺寸增加,影像大小也會增加。如果 div 元素的尺寸減小,影像大小也會減小。

<html>
<head>
   <style>
      .image {
         width: 30%;
         min-height: 30%;
         margin: 0 auto;
         border: 3px solid red;
         padding: 10px;
         background-image: url("https://tutorialspoint.tw/python_pillow/images/tutorials_point.jpg");
         background-size: contain;
         background-repeat: no-repeat;
      }
   </style>
</head>
<body>
   <h3> Using the <i> background-size CSS property </i> to resize image proportionally </h3>
   <div class = "image"></div>
</body>
</html>

使用者學習瞭如何按比例更改影像尺寸。在這裡,我們只需要將影像尺寸設定為百分比,而不是畫素或 rem。此外,使用者還可以使用“background-size” CSS 屬性來按比例更改背景影像的尺寸。

更新於:2023年4月18日

424 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告