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

การตั้งค่ารูปทรง Radial Gradients ด้วย CSS

Radial Gradient Shape: Circle vs Ellipse

พารามิเตอร์แรกของ radial-gradient() กำหนดรูปทรง: circle (วงกลมสมบูรณ์) หรือ ellipse (default, ไข่ตาม aspect ratio ของกล่อง)

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

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    #radial {
      height: 200px; width: 300px;
      background-image: radial-gradient(ellipse, rgb(217, 255, 0), rgb(255, 0, 0), rgb(14, 239, 255));
    }
  </style>
</head>
<body>
  <h1>Radial Gradient Shape Example</h1>
  <div id="radial"></div>
</body>
</html>

Shape Comparison

  • circle: รัศมีเท่าทุกทิศ ทรงกลมสมบูรณ์ – ใช้ radial-gradient(circle, ...) หรือ radial-gradient(circle 100px at center, ...)
  • ellipse (default): กว้าง/สูงตาม container – ใช้ radial-gradient(ellipse, ...) หรือไม่ระบุก็ได้

รวม Shape + Size + Position

radial-gradient(circle closest-side at 20% 30%, red, yellow, blue)
/* circle, size=closest-side, position=20% 30% */

ตัวอย่างผลลัพธ์ต่างกัน

.box { width: 300px; height: 200px; }
.circle { background: radial-gradient(circle at center, red, blue); }      /* วงกลมกลางกล่อง */
.ellipse { background: radial-gradient(ellipse at center, red, blue); }    /* ไข่เต็มกล่อง */
.circle-closest { background: radial-gradient(circle closest-side at center, red, blue); } /* วงกลมสัมผัสขอบใกล้สุด */
.ellipse-farthest { background: radial-gradient(ellipse farthest-corner at center, red, blue); } /* default */

การประยุกต์

  • Spotlight effect: radial-gradient(circle 50px at mouseX mouseY, rgba(255,255,255,0.3), transparent) – ใช้ JS update position
  • Vignette: radial-gradient(ellipse farthest-corner at center, transparent 70%, rgba(0,0,0,0.5))
  • Progress ring: conic-gradient ดีกว่า