You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用CSS为伪元素生成的SVG图标添加悬浮提示文本

纯CSS实现伪元素图标的悬浮提示方案

由于无法修改HTML标记,我们可以利用CSS伪元素和hover状态来实现自定义悬浮提示,以下是两种可行方案:

方案一:hover按钮整体显示提示

这种方案会在鼠标悬停按钮(包括图标)时显示提示文本:

/* 给父元素设置相对定位,用于tooltip的绝对定位 */
#edit-actions--3 {
  position: relative;
}

/* 保留你原有的图标样式 */
#edit-actions--3::after{
    content: url("/themes/custom/mytheme/assets/icons/tooltip.svg");
    display: inline-block;
    width: 2%;
    margin-left: 0.4rem;
    cursor: help; /* 显示帮助光标,提示可交互 */
}

/* 定义tooltip的基础样式,初始隐藏 */
#edit-actions--3::before {
    content: "this is a tooltip icon"; /* 提示文本 */
    position: absolute;
    bottom: 100%; /* 提示显示在按钮上方 */
    left: 50%;
    transform: translateX(-50%); /* 水平居中 */
    background-color: #333;
    color: #fff;
    padding: 0.3rem 0.6rem;
    border-radius: 4px;
    font-size: 0.8rem;
    white-space: nowrap; /* 防止文本换行 */
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.2s, visibility 0.2s; /* 添加过渡动画 */
    z-index: 100; /* 确保tooltip在最上层 */
}

/* hover按钮时显示tooltip */
#edit-actions--3:hover::before {
    opacity: 1;
    visibility: visible;
}

方案二:仅hover图标时显示提示

如果希望只有鼠标悬停在图标上时才触发提示,可以通过pointer-events控制鼠标事件的接收范围:

#edit-actions--3 {
  position: relative;
  pointer-events: none; /* 让按钮主体不接收鼠标事件 */
}

#edit-actions--3::after{
    content: url("/themes/custom/mytheme/assets/icons/tooltip.svg");
    display: inline-block;
    width: 2%;
    margin-left: 0.4rem;
    cursor: help;
    pointer-events: auto; /* 仅让图标接收鼠标事件 */
}

#edit-actions--3::before {
    content: "this is a tooltip icon";
    position: absolute;
    top: calc(100% + 0.5rem); /* 提示显示在图标下方 */
    left: calc(100% + 1rem); /* 调整提示的水平位置 */
    background-color: #333;
    color: #fff;
    padding: 0.3rem 0.6rem;
    border-radius: 4px;
    font-size: 0.8rem;
    white-space: nowrap;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.2s, visibility 0.2s;
    z-index: 100;
}

/* 仅hover图标时显示tooltip */
#edit-actions--3:hover::before {
    opacity: 1;
    visibility: visible;
}

样式调整说明

你可以根据需求修改以下属性来调整tooltip的位置和外观:

  • top/bottom/left/right:控制tooltip的显示位置
  • background-color/color:修改背景色和文字颜色
  • padding/font-size:调整内边距和文字大小
  • border-radius:设置圆角

内容的提问来源于stack exchange,提问作者Rick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:07:42