工具提示 Tooltip
纯 CSS 实现 tooltip、四个方向箭头、淡入动画
工具提示 Tooltip
纯 CSS 实现鼠标悬停时出现的提示框——不需要 JavaScript。
学完本章你将: 掌握四个方向的 tooltip、箭头、淡入动画。
基本 tooltip
html
<div class="tooltip">
悬停我
<span class="tooltip-text">这是提示内容</span>
</div>
css
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted #333;
}
.tooltip-text {
visibility: hidden;
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background: #333;
color: white;
padding: 6px 12px;
border-radius: 4px;
white-space: nowrap;
font-size: 14px;
}
.tooltip:hover .tooltip-text { visibility: visible; }
添加箭头
css
.tooltip-text::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
border: 5px solid transparent;
border-top-color: #333;
}
四个方向
css
/* 上方 */
.top { bottom: 125%; }
/* 下方 */
.bottom { top: 125%; }
.bottom::after {
bottom: 100%;
border-top-color: transparent;
border-bottom-color: #333;
}
/* 左侧 */
.left { right: 110%; top: 50%; transform: translateY(-50%); }
/* 右侧 */
.right { left: 110%; top: 50%; transform: translateY(-50%); }