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

Cách định vị tooltip đúng vị trí với CSS (top, right, bottom, left)

Định vị tooltip 4 hướng với CSS

Tooltip có thể hiển thị ở 4 vị trí quanh phần tử cha: **trên, dưới, trái, phải**. Kỹ thuật cốt lõi: kết hợp top/right/bottom/left với transform để căn giữa chính xác.

Ví dụ: Tooltip bên phải (Right)

<!DOCTYPE html>
<html>
<head>
  <style>
    .mytooltip .mytext {
      visibility: hidden;
      width: 140px;
      background-color: blue;
      color: #fff;
      z-index: 1;
      top: 50%;              /* Căn giữa dọc */
      left: 100%;            /* Bên phải cha */
      transform: translateY(-50%); /* Căn chính giữa dọc */
      margin-left: 10px;     /* Khoảng cách gap */
      text-align: center;
      border-radius: 6px;
      padding: 8px;
      position: absolute;
      opacity: 0;
      transition: opacity 0.3s, visibility 0.3s;
    }
    .mytooltip {
      position: relative;
      display: inline-block;
    }
    .mytooltip:hover .mytext {
      visibility: visible;
      opacity: 1;
    }
    /* Mũi tên trỏ trái */
    .mytooltip .mytext::after {
      content: "";
      position: absolute;
      top: 50%;
      right: 100%;
      margin-top: -5px;
      border-width: 5px;
      border-style: solid;
      border-color: transparent blue transparent transparent;
    }
  </style>
</head>
<body>
  <div class="mytooltip">
    Hover me
    <span class="mytext">Tooltip bên phải</span>
  </div>
</body>
</html>

Bảng định vị 4 hướng

Vị tríTooltip CSSMũi tên (::after)
Phải (Right) top: 50%; left: 100%; transform: translateY(-50%); margin-left: 10px; right: 100%; border-color: transparent blue transparent transparent;
Trái (Left) top: 50%; right: 100%; transform: translateY(-50%); margin-right: 10px; left: 100%; border-color: transparent transparent transparent blue;
Trên (Top) bottom: 100%; left: 50%; transform: translateX(-50%); margin-bottom: 10px; bottom: 100%; border-color: blue transparent transparent transparent;
Dưới (Bottom) top: 100%; left: 50%; transform: translateX(-50%); margin-top: 10px; top: 100%; border-color: transparent transparent blue transparent;

Mẹo chuyên nghiệp

  • Dùng opacity + transition thay vì visibility đơn thuần để có hiệu ứng fade mượt.
  • Thêm pointer-events: none cho tooltip tránh chặn click.
  • Xử lý edge case (viewport boundary) cần JavaScript hoặc CSS anchor-positioning (mới).