Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Giữ tỷ lệ khung hình (Aspect Ratio) của phần tử với CSS

Để phần tử giữ tỷ lệ khung hình (ví dụ 16:9, 4:3, 1:1) khi resize, dùng kỹ thuật padding-top percentage hoặc thuộc tính mới aspect-ratio.

Cách 1: Padding-top hack (Tương thích rộng)

<!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%; /* 4:3 = 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 example (4:3)</h1>
<div class="aspectContainer">
  <div class="aspectText">4:3 Aspect ratio</div>
</div>
<h2>Resize cửa sổ để thấy tỷ lệ 4:3 được giữ nguyên</h2>
</body>
</html>

Cách 2: Thuộc tính aspect-ratio (Hiện đại, CSS2021+)

.aspectContainer {
  width: 100%;
  aspect-ratio: 16 / 9; /* Hoặc 4 / 3, 1 / 1 */
  background-color: rgb(191, 66, 216);
}
/* Không cần padding hack, nội dung trực tiếp trong container */

Bảng tỷ lệ phổ biến

Tỷ lệPadding-topaspect-ratio
16:9 (Video)56.25%16/9
4:3 (Ảnh cũ)75%4/3
1:1 (Vuông)100%1/1
3:2 (Ảnh 35mm)66.66%3/2
21:9 (Ultrawide)42.85%21/9

Ứng dụng

  • Container video responsive (iframe YouTube, Vimeo)
  • Ảnh placeholder giữ tỷ lệ trước khi load
  • Card grid cùng tỷ lệ
  • Map embed