Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo mũi tên tooltip bên trái (arrow left) với CSS

Tooltip bên phải có mũi tên trỏ trái

Khi tooltip hiển thị **bên phải** phần tử cha, mũi tên cần trỏ **về bên trái** (chạm vào cha). Kỹ thuật: dùng pseudo-element `::after` với border triangle.

Ví dụ hoàn chỉnh

<!DOCTYPE html>
<html>
<head>
  <style>
    .mytooltip .mytext {
      visibility: hidden;
      width: 140px;
      background-color: blue;
      color: #fff;
      z-index: 1;
      top: -5px;
      left: 110%;           /* 100% + gap 10% */
      text-align: center;
      border-radius: 6px;
      padding: 5px 0;
      position: absolute;
    }
    .mytooltip {
      position: relative;
      display: inline-block;
      margin-left: 50px;    /* Khoảng cách lề trái trang */
    }
    /* Mũi tên trỏ TRÁI (chạm vào cha) */
    .mytooltip .mytext::after {
      content: "";
      position: absolute;
      top: 50%;
      right: 100%;          /* Đính vào cạnh phải tooltip */
      margin-top: -5px;     /* Căn giữa dọc (nửa border-width) */
      border-width: 6px;
      border-style: solid;
      /* Màu: trong suốt - blue - trong suốt - trong suốt */
      border-color: transparent blue transparent transparent;
    }
    .mytooltip:hover .mytext {
      visibility: visible;
    }
  </style>
</head>
<body>
  <div class="mytooltip">
    Keep mouse cursor over me
    <span class="mytext"> My Tooltip text</span>
  </div>
</body>
</html>

Giải thích kỹ thuật Border Triangle

CSS triangle tạo bằng border của element width=0, height=0:

.arrow {
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-right-color: blue;  /* Mũi tên trỏ trái */
}
Hướng mũi tênBorder color pattern
Trỏ Trái (←)border-color: transparent blue transparent transparent; (right color)
Trỏ Phải (→)border-color: transparent transparent transparent blue; (left color)
Trỏ Lên (↑)border-color: transparent transparent blue transparent; (bottom color)
Trỏ Xuống (↓)border-color: blue transparent transparent transparent; (top color)

Căn giữa mũi tên

  • top: 50%; margin-top: -6px; (nửa border-width) cho mũi tên ngang.
  • left: 50%; margin-left: -6px; cho mũi tên dọc.

Cải tiến: Dùng transform thay margin

.mytooltip .mytext::after {
  top: 50%;
  right: 100%;
  transform: translateY(-50%);  /* Căn giữa chính xác, không phụ thuộc border-width */
  border: 6px solid transparent;
  border-right-color: blue;
}