ฟังก์ชัน scale() ใน CSS Transform ใช้ขยายหรือย่อ element บน 2D plane โดยไม่กระทบ layout ของ element อื่น (ไม่ทำ reflow)
รูปแบบไวยากรณ์
transform: scale(sx, sy); /* sx = scale X, sy = scale Y */ transform: scale(s); /* sx = sy = s (uniform scaling) */ transform: scaleX(sx); /* แค่แกน X */ transform: scaleY(sy); /* แค่แกน Y */
scale(1)= ขนาดเดิมscale(2)= ใหญ่ขึ้น 2 เท่าscale(0.5)= เล็กลงครึ่งหนึ่งscale(-1)= กลับด้าน (mirror)
ตัวอย่างที่ 1: ขยาย 1.2 เท่า
<!DOCTYPE html>
<html>
<head>
<style>
.translate_img { transform: translate(100px, 10%); }
.scale_img {
transform: scale(1.2);
background-color: yellow;
}
</style>
</head>
<body>
<h1>Learn</h1>
<img class="translate_img" src="https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png" alt="MongoDB">
<img class="scale_img" src="https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png" alt="MongoDB">
</body>
</html>
ตัวอย่างที่ 2: ย่อ 0.3 เท่า
<!DOCTYPE html>
<html>
<head>
<style>
.translate_img { transform: translate(100px, 10%); }
.scale_img { transform: scale(0.3); }
</style>
</head>
<body>
<h1>Learn</h1>
<img class="translate_img" src="..." alt="MongoDB">
<img class="scale_img" src="..." alt="MongoDB">
</body>
</html>
ข้อดีของ scale():
- GPU accelerated (compositor thread)
- ไม่ทำให้เกิด layout reflow
- คุณภาพรูปภาพดีกว่าการเปลี่ยน width/height (ไม่บีบอัดพิกเซล)
- สามารถรวมกับ transform อื่นได้:
transform: translate(50px, 50px) scale(1.5) rotate(10deg);
transform-origin: จุดศูนย์กลางการ scale (default: center center) เปลี่ยนได้ด้วย transform-origin: top left; เป็นต้น