Mũi tên CSS được tạo bằng kỹ thuật border hack: phần tử width/height = 0, dùng border tạo tam giác.
Ví dụ mã nguồn
<!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; }
i {
border: solid rgb(62, 19, 182);
border-width: 0 6px 6px 0; /* Chỉ có border dưới và phải */
display: inline-block;
padding: 3px;
}
p { font-size: 18px; font-weight: 500; }
.rightArrow { transform: rotate(-45deg); } /* ▶ */
.leftArrow { transform: rotate(135deg); } /* ◀ */
.upArrow { transform: rotate(-135deg); } /* ▲ */
.downArrow { transform: rotate(45deg); } /* ▼ */
</style>
</head>
<body>
<h2>CSS Arrows</h2>
<p>Mũi tên phải: <i class="rightArrow"></i></p>
<p>Mũi tên trái: <i class="leftArrow"></i></p>
<p>Mũi tên lên: <i class="upArrow"></i></p>
<p>Mũi tên xuống: <i class="downArrow"></i></p>
</body>
</html>
Giải thích kỹ thuật Border Hack
/* Nguyên lý: element 0x0, border tạo 4 tam giác */
/* Chỉ giữ 2 border liền kề, 2 border kia = transparent */
.arrow {
width: 0; height: 0;
border: 10px solid transparent; /* Reset tất cả */
}
.arrow-up { border-bottom-color: #000; } /* ▲ */
.arrow-down { border-top-color: #000; } /* ▼ */
.arrow-left { border-right-color: #000; } /* ◀ */
.arrow-right { border-left-color: #000; } /* ▶ */
Mũi tên có viền (Bordered Arrows)
.arrow-bordered {
position: relative;
}
.arrow-bordered::before,
.arrow-bordered::after {
content: ''; position: absolute; width: 0; height: 0; border: 10px solid transparent;
}
.arrow-bordered::before { /* Viền ngoài */
border-bottom-color: #333; bottom: -20px; left: 50%; transform: translateX(-50%);
}
.arrow-bordered::after { /* Mũi tên trong */
border-bottom-color: white; bottom: -18px; left: 50%; transform: translateX(-50%);
}
Mũi tên Unicode (Thay thế đơn giản)
Đơn giản hơn: dùng ký tự Unicode trực tiếp trong HTML/CSS content:
.arrow-right::before { content: "\2192"; } /* → */
.arrow-left::before { content: "\2190"; } /* ← */
.arrow-up::before { content: "\2191"; } /* ↑ */
.arrow-down::before { content: "\2193"; } /* ↓ */
/* Hoặc: ▶ ▼ ◀ ▲ (Black triangles) */
So sánh
| Cách | Ưu điểm | Nhược điểm |
|---|---|---|
| Border hack | Pure CSS, scale tốt, màu tùy ý | Phức tạp, khó canh giữa text |
| Unicode | Đơn giản, scale với font-size, căn dòng dễ | Giới hạn style (màu, độ dày) |
| SVG/Icon font | Đẹp, nhiều biến thể, scale tốt | Cần file/font bên ngoài |
| clip-path | Hình dạng tùy ý, responsive | Hỗ trợ IE không tốt |