首頁  >  文章  >  web前端  >  使用 CSS 按比例調整圖片大小

使用 CSS 按比例調整圖片大小

WBOY
WBOY轉載
2023-09-08 08:01:071590瀏覽

使用 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://www.tutorialspoint.com/python_pillow/images/tutorials_point.jpg" alt = "logo">
   </div>
</body>
</html>

範例

在下面的範例中,我們使用了「object-fit: contains」CSS 屬性來按比例縮小影像的大小。在這裡,我們設定了圖像的父 div 元素的比例寬度。此外,我們也為「img」元素使用了「object-fit: contains」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://www.tutorialspoint.com/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://www.tutorialspoint.com/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 屬性按比例來變更背景圖像的尺寸。

以上是使用 CSS 按比例調整圖片大小的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除