CSS - aspect-ratio 屬性



CSS 的aspect-ratio屬性定義了元素盒子的期望寬高比。當父容器或視口大小改變時,此屬性非常有用,瀏覽器會重新調整元素的尺寸以保持寬高比。

語法

aspect-ratio: auto | number (width) / number (height) | initial | inherit;

屬性值

描述
auto 指定不設定特定比例。
number / number 第一個數字指定寬度,第二個數字指定高度的縱橫比。如果沒有指定數字,則預設為 1。
initial 將屬性設定為其初始值。
inherit 從父元素繼承屬性。

CSS Aspect Ratio 屬性示例

以下示例解釋了使用不同值的aspect-ratio屬性。

使用 auto 值的縱橫比

如果不需要保持特定的寬高比,我們可以簡單地使用 auto 值,它指定不強制執行嚴格的寬高比。以下示例顯示了這一點。

示例

<!DOCTYPE html>
<html>

<head>
   <style>
      img {
         border: 5px solid red;
         width: 300px;
         aspect-ratio: auto;
      }
   </style>
</head>

<body>
   <h2>
      CSS aspect-ratio Property
   </h2>
   <img src="/css/images/orange-flower.jpg" alt="flower-image">
</body>

</html>

使用寬度和高度值的縱橫比

為了保持固定的寬高比,我們可以指定寬度和高度值。如果未提及高度值,則將其視為 1。以下示例顯示了不同的縱橫比。

示例

<!DOCTYPE html>
<html>

<head>
   <style>
      div img {
         display: block;
         margin: 15px;
      }

      #img1 {
         border: 5px solid red;
         width: 300px;
         aspect-ratio: 1/1;
      }

      #img2 {
         border: 5px solid red;
         width: 300px;
         aspect-ratio: 4/3;
      }

      #img3 {
         border: 5px solid red;
         width: 300px;
         aspect-ratio: 16/9;
      }
   </style>
</head>

<body>
   <h2>
      CSS aspect-ratio Property
   </h2>
   <div>
      <label>Square size (1:1) aspect ratio</label>
      <img src="/css/images/orange-flower.jpg" 
      alt="flower-image" id="img1">
      <label>Standard size (4:3) aspect ratio</label>
      <img src="/css/images/orange-flower.jpg" 
      alt="flower-image" id="img2">
      <label>Widescreen size (16:9) aspect ratio</label>
      <img src="/css/images/orange-flower.jpg" 
      alt="flower-image" id="img3">
   </div>

</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
aspect-ratio 88 88 89 15 74
css_properties_reference.htm
廣告
© . All rights reserved.