利用 position: relative 父容器 + position: absolute 子提示層 + :hover 顯示控制,零 JavaScript 實現滑鼠懸停彈出提示層。提示層內可放文字、圖片、列表等任意內容,擴展性極強。
<a class="tooltip-trigger" href="#">
觸發文字
<span class="tooltip-content">提示層內容</span>
</a>
.tooltip-trigger {
position: relative; /* 建立定位上下文 */
display: inline-block; /* 包裹內容 */
text-decoration: none;
color: #0066cc;
}
.tooltip-content {
display: none; /* 預設隱藏 */
position: absolute;
top: -1px; left: 100%; /* 相對觸發器定位:右側對齊 */
width: 130px; height: 60px;
padding: 8px;
border: 1px solid #eee;
background: #fff;
z-index: 10;
box-shadow: 0 2px 8px rgba(0,0,0,.1);
}
.tooltip-trigger:hover .tooltip-content { display: block; }
<style>
.tooltip-trigger {
position: relative; display: inline-block;
width: 158px; height: 20px; line-height: 20px;
border: 1px solid #eee; background: #fff;
text-align: center; color: #0066cc; text-decoration: none;
}
.tooltip-trigger:hover { z-index: 2; background: #fff; }
.tooltip-trigger span {
display: none; position: absolute;
top: -1px; left: 158px; /* 緊貼右側 */
width: 130px; height: 60px;
border: 1px solid #eee; z-index: 1;
padding: 5px; background: #fff;
}
</style>
<div>
<a class="tooltip-trigger" href="#">
腳本之家
<span>一個高品質腳本資料網站</span>
</a>
</div>
<div>
<a class="tooltip-trigger" href="#">
網頁特效庫
<span>給你實用的 CSS 代碼</span>
</a>
</div>
.tooltip-content::before {
content: ''; position: absolute;
left: -8px; top: 50%; margin-top: -4px;
border: 4px solid transparent;
border-right-color: #eee; /* 邊框色 */
}
.tooltip-content::after {
content: ''; position: absolute;
left: -7px; top: 50%; margin-top: -4px;
border: 4px solid transparent;
border-right-color: #fff; /* 背景色,疊在邊框上形成箭頭 */
}
.tooltip-content {
opacity: 0; transform: translateX(-10px);
transition: opacity 0.2s, transform 0.2s;
pointer-events: none;
}
.tooltip-trigger:hover .tooltip-content {
opacity: 1; transform: translateX(0);
pointer-events: auto;
}
純 CSS 無法檢測視口邊界。若需「右側不夠空間則左側顯示」,需 JS 計算 getBoundingClientRect() 動態加類名 .tooltip-left。
aria-describedby="tooltip-id"role="tooltip" id="tooltip-id".tooltip-trigger:focus .tooltip-content@media (hover: none) 下改為點擊切換| 維度 | CSS Only | JS 庫 (Tippy, Popper) |
|---|---|---|
| 體積 | ~200 bytes | 5-15 KB |
| 智能定位/防遮擋 | ❌ | ✅ |
| 動畫/過渡控制 | 基礎 | 豐富 |
| 觸屏/鍵盤無障礙 | 需手動補 | 內建 |
| 內容動態載入 | ❌ | ✅ |
| 適用場景 | 靜態提示、簡單幫助文本、零依賴要求 | 複雜交互、表單驗證、下拉選單、數據密集提示 |
簡單場景,**CSS Tooltip 完勝**:零依賴、零運行時、瀏覽器原生效能。複雜場景再引入 Popper.js/Tippy.js 不遲。