Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีรักษาอัตราส่วนภาพ (Aspect Ratio) ขององค์ประกอบด้วย CSS

Aspect Ratio ด้วย Padding-Top Hack (รองรับทุก Browser)

ก่อนมี property aspect-ratio ใช้เทคนิค padding-top: % บน container (position: relative) แล้ววางเนื้อหา position: absolute ครอบเต็ม พื้นที่ padding จะสร้างความสูงสัมพันธ์กับความกว้าง

โค้ดตัวอย่าง (4:3)

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    .aspectContainer {
      background-color: rgb(191, 66, 216);
      position: relative; width: 100%; padding-top: 75%; /* 3/4 = 75% */
    }
    .aspectText {
      position: absolute; top: 0; left: 0; bottom: 0; right: 0;
      text-align: center; font-size: 20px; color: white;
      display: flex; align-items: center; justify-content: center;
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Aspect Ratio 4:3</h1>
  <div class="aspectContainer">
    <div class="aspectText">4:3 Aspect ratio</div>
  </div>
  <h2>ลอง resize หน้าต่าง ดูอัตราส่วนคงที่</h2>
</body>
</html>

สูตร Padding-Top

อัตราส่วนPadding-Top
16:9 (วิดีโอ)56.25%
4:3 (โทรทัศน์เก่า)75%
1:1 (สี่เหลี่ยมจัตุรัส)100%
3:2 (ภาพถ่าย)66.66%
21:9 (ซินีม่า)42.85%

วิธีทันสมัย: aspect-ratio property

.video { aspect-ratio: 16 / 9; width: 100%; }

รองรับ Chrome 88+, Firefox 87+, Safari 15+, Edge 88+ – ใช้ได้จริงแล้วในโปรดักชัน รวมกับ object-fit: cover สำหรับ <img>/<video>