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

วิธาเพิ่ม Transition เมื่อ Hover ด้วย CSS

Hover Transition: ทำให้การเปลี่ยนแปลงสไตล์นุ่มนวล

ใช้ transition property บนสถานะปกติ (ไม่ใช่ :hover) เพื่อกำหนด property ที่จะ transition, duration, easing, delay เมื่อ hover เข้า/ออก จะนุ่มนวล

โค้ดตัวอย่าง

<!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; padding: 20px; }
    .scaleBtn {
      display: inline-block; background-color: #0c1377; border: none; color: white;
      padding: 16px 32px; text-align: center; font-size: 16px;
      transition: 0.3s; margin: 20px;
    }
    .scaleBtn:hover { transform: scale(1.5); }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Transition on Hover</h1>
  <button class="scaleBtn">Hover Here</button>
</body>
</html>

Transition Syntax

transition: property duration timing-function delay;
/* ตัวอย่าง */
transition: background-color 0.3s ease, transform 0.2s ease-out 0.1s;
/* Shorthand: all 0.3s ease 0s */

Property ที่ Transition ได้ (Animatable)

  • Colors: color, background-color, border-color, outline-color
  • Dimensions: width, height, padding, margin, border-width
  • Transform: transform (scale, rotate, translate, skew)
  • Opacity: opacity
  • Font: font-size, line-height, letter-spacing
  • Shadow: box-shadow, text-shadow

Performance Tips

  • ใช้ transform และ opacity หลัก – GPU accelerated, ไม่ trigger layout/repaint
  • หลีกเลี่ยง transition width/height/top/left – ทำ reflow ทุกเฟรม
  • will-change: transform บอก browser เตรียม GPU layer ล่วงหน้า

Accessibility

เพิ่ม @media (prefers-reduced-motion: reduce) { .scaleBtn { transition: none; } } ปิด animation ให้ผู้ที่ตั้งค่าลดการเคลื่อนไหว