โดยการระบุ padding ขององค์ประกอบเป็นเปอร์เซ็นต์ เราสามารถรักษาอัตราส่วนภาพ (Aspect Ratio) ได้
สำหรับสิ่งนี้ ใช้คุณสมบัติ padding ใน CSS:
- padding-bottom - ระบุ padding ด้านล่าง
- padding-top - ระบุ padding ด้านบน
- padding-left - ระบุ padding ด้านซ้าย
- padding-right - ระบุ padding ด้านขวา
- padding - shorthand สำหรับคุณสมบัติข้างต้นทั้งหมด
ตัวอย่างที่ 1: อัตราส่วน 1:1 (Square)
<!DOCTYPE html>
<html>
<head>
<style>
#demo {
padding-top: 100%;
box-shadow: 0 0 24px steelblue;
position: relative;
width: 100%;
}
div > div {
margin: 10px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
text-align: center;
}
</style>
</head>
<body>
<p>Watch the below div</p>
<div id="demo">
<div>Fun Ratio!</div>
</div>
</body>
</html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:

แม้หลังจากปรับขนาดหน้าต่าง อัตราส่วนก็ยังคงเป็น 1:1

ตัวอย่างที่ 2: อัตราส่วน 16:9 สำหรับ YouTube Embed
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 10%;
padding-top: 56.25%; /* 16:9 ratio */
height: 0px;
position: relative;
box-shadow: 0 0 0 20px antiquewhite;
}
iframe {
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div>
<iframe src="https://www.youtube.com/embed/0cwk9UMLnWE" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</body>
</html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:
