萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 實現帶三角箭頭的提示框 (Tooltip)

核心原理:CSS 三角形邊框技巧

利用零寬高元素的粗邊框,將三邊設為透明,保留一邊顏色,形成三角形。

HTML 結構

<div class="tooltip">
  <div class="content">
    <div class="title">提示標題</div>
    <div class="main">詳細說明內容...</div>
  </div>
  <s><i></i></s>   <!-- s=外層三角(邊框色), i=內層三角(背景色) -->
</div>

關鍵 CSS

.tooltip {
  position: absolute; top: 555px; left: 200px;
  width: 405px; height: 335px;
  display: none; /* JS 控制顯示 */
}
.tooltip .content {
  position: absolute; inset: 0;
  border: 1px solid #fa0505;
  border-radius: 3px;
  background: #fefef4; padding: 5px;
}

/* 外層三角 (邊框色) */
.tooltip s {
  position: absolute; top: -20px; left: 50px;
  width: 0; height: 0; font-size: 0; line-height: 0;
  border: 10px dashed transparent;
  border-bottom-style: solid;
  border-bottom-color: #fa0505;
}

/* 內層三角 (背景色) 向下覆蓋 1px 形成銳利尖角 */
.tooltip i {
  position: absolute; top: -9px; left: -10px;
  width: 0; height: 0; font-size: 0; line-height: 0;
  border: 10px dashed transparent;
  border-bottom-style: solid;
  border-bottom-color: #fefef4;
}

現代簡化:單元素 + ::before/::after

.tooltip-modern {
  position: relative;
  padding: 12px 16px;
  background: #fefef4;
  border: 1px solid #fa0505;
  border-radius: 6px;
}
.tooltip-modern::before,
.tooltip-modern::after {
  content: '';
  position: absolute; left: 50px;
  border: 10px solid transparent;
  border-bottom-style: solid;
}
.tooltip-modern::before {
  top: -20px; border-bottom-color: #fa0505; /* 邊框三角 */
}
.tooltip-modern::after {
  top: -18px; border-bottom-color: #fefef4;  /* 背景三角 */
}

減少兩個無語義標籤 ``,結構更乾淨。

定位輔助:JS 計算位置

function showTooltip(trigger, tooltip) {
  const rect = trigger.getBoundingClientRect();
  tooltip.style.top = rect.bottom + window.scrollY + 8 + 'px';
  tooltip.style.left = rect.left + window.scrollX + 'px';
  tooltip.style.display = 'block';
}

配合 `Popper.js` 或 `Floating UI` 庫可處理邊界檢測、翻轉、滾動跟隨等複雜邏輯。

copyright © 萬盛學電腦網 all rights reserved