CSS clip-path property ทำให้เราตัดรูปทรง Element ได้ตาม Path ที่กำหนด สร้างสามเหลี่ยมได้ง่ายด้วย polygon() ไม่ต้องใช้ Border Hack แบบเก่า
Syntax
selector {
clip-path: polygon(x1 y1, x2 y2, x3 y3);
}
ตัวอย่างที่ 1: สามเหลี่ยมมุมบนกึ่งกลาง (Upward Triangle)
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 10%;
border-radius: 2%;
width: 10%;
box-shadow: inset 0 0 80px violet;
clip-path: polygon(50% 0, 100% 100%, 0% 100%);
}
</style>
</head>
<body>
<div></div>
</body>
</html>
clip-path: polygon(50% 0, 100% 100%, 0% 100%)
50% 0 - จุดบนกึ่งกลาง (Top Center)100% 100% - มุมล่างขวา (Bottom Right)0% 100% - มุมล่างซ้าย (Bottom Left)
ตัวอย่างที่ 2: สามเหลี่ยมจาก Border (วิธีเก่า)
<!DOCTYPE html>
<html>
<head>
<style>
div { display: flex; margin: 10px 0 20px; }
div > div {
height: 12px;
border-top: 40px ridge orange;
border-right: 20px solid white;
border-bottom: 60px ridge cornflowerblue;
border-left: 80px solid white;
}
</style>
</head>
</body>
<html>
หลักการ: Element ไม่มีขนาด (width: 0, height: 0) ใช้ Border สร้างสามเหลี่ยมจากขอบที่เจอกัน
Clip-path Polygon สำหรับสามเหลี่ยมทุกทิศทาง
| ทิศทาง | Polygon Points | Visual |
|---|---|---|
| Up (▲) | polygon(50% 0, 100% 100%, 0 100%) | ยอดบนกึ่งกลาง |
| Down (▼) | polygon(0 0, 100% 0, 50% 100%) | ยอดล่างกึ่งกลาง |
| Left (◄) | polygon(100% 0, 0 50%, 100% 100%) | ยอดซ้ายกึ่งกลาง |
| Right (►) | polygon(0 0, 100% 50%, 0 100%) | ยอดขวากึ่งกลาง |
| Equilateral | polygon(50% 0%, 100% 86.6%, 0% 86.6%) | สามเหลี่ยมด้านเท่า |
Clip-path Shapes อื่นๆ ที่น่าสนใจ
/* Circle */ clip-path: circle(50% at 50% 50%); /* Ellipse */ clip-path: ellipse(50% 30% at 50% 50%); /* Pentagon */ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); /* Star (5 points) */ clip-path: polygon( 50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35% ); /* Speech Bubble */ clip-path: polygon(0 0, 100% 0, 100% 75%, 75% 75%, 50% 100%, 25% 75%, 0 75%);
การใช้งานกับ Images และ Gradients
.triangle-image {
width: 200px; height: 200px;
background: url('photo.jpg') center/cover;
clip-path: polygon(50% 0, 100% 100%, 0 100%);
}
.triangle-gradient {
width: 100px; height: 100px;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
clip-path: polygon(50% 0, 100% 100%, 0 100%);
}
Animation กับ Clip-path
.triangle:hover {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
transition: clip-path 0.3s ease;
}
/* Morphing Triangle */
@keyframes morph {
0% { clip-path: polygon(50% 0, 100% 100%, 0 100%); }
50% { clip-path: polygon(50% 0, 100% 50%, 0 100%); }
100% { clip-path: polygon(50% 0, 100% 100%, 0 100%); }
}
Browser Support
- Chrome 55+, Firefox 54+, Safari 10.1+, Edge 79+
- ต้องใช้ Prefix
-webkit-clip-pathสำหรับ Safari เก่า - IE: ไม่รองรับ
- ตรวจสอบได้ที่ Can I Use
Tools ช่วยสร้าง Clip-path
- Clippy - CSS Clip Path Maker (Visual Editor)
- CSS Clip Path Generator
- Firefox DevTools มี Clip-path Editor ใน Inspector