ตัวอย่างการสร้างแอนิเมชันเปลี่ยนค่า max-height (ความสูงสูงสุด) ของ element พร้อม overflow auto
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 350px;
background-color: orange;
overflow: auto;
border: 1px solid black;
animation: myanim 3s infinite;
}
@keyframes myanim {
30% {
max-height: 100px;
}
}
</style>
</head>
<body>
<h1>Example of max-height</h1>
<div>
<p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text.</p>
</div>
</body>
</html>
คำอธิบาย: กล่องเริ่มต้นไม่มี max-height (ขยายตามเนื้อหา) ที่ 30% max-height จะจำกัดที่ 100px ทำให้กล่องหดสูงลง และเนื้อหาที่เกินจะมี scrollbar (overflow: auto)
การประยุกต์ใช้: สร้าง accordion, collapsible panel, read more/less animation
แนวทางที่ดีกว่าสำหรับ accordion: ใช้ max-height: 0 ถึง max-height: 1000px (ค่ามากพอครอบเนื้อหา) ร่วมกับ transition แทน keyframes เพื่อควบคุมได้ง่ายขึ้นด้วย JavaScript toggle class