使用css的attr()写一个类似a标签title的提示框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Tooltip with attr()</title>
<style>
/* Basic styling for the element */
span {
border-bottom: 1px dotted #000;
cursor: help;
position: relative;
}
/* Tooltip styling */
span::after {
content: attr(data-tooltip); /* Get content from data-tooltip attribute */
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: 100%;
margin-bottom: 5px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 5px;
white-space: nowrap; /* Prevent tooltip text from wrapping */
opacity: 0; /* Initially hidden */
visibility: hidden; /* Initially hidden */
transition: opacity 0.3s, visibility 0.3s; /* Smooth transition */
pointer-events: none; /* Prevent tooltip from interfering with clicks */
z-index: 1; /* Ensure tooltip is on top */
}
/* Show tooltip on hover */
span:hover::after {
opacity: 1;
visibility: visible;
}
</style>
</head>
<body>
<p>Hover over the <span data-tooltip="This is a tooltip!">highlighted text</span> to see the tooltip.</p>
<p>Another example: <span data-tooltip="A different tooltip message.">more highlighted text</span>.</p>
</body>
</html>
Explanation and Key Improvements:
data-tooltip
attribute: The tooltip content is stored in thedata-tooltip
attribute of the<span>
. This makes the HTML cleaner and separates content from presentation.attr(data-tooltip)
in CSS: Thecontent
property of the::after
pseudo-element usesattr(data-tooltip)
to dynamically pull the tooltip text from the HTML.- Positioning: The tooltip is positioned absolutely relative to the
<span>
.left: 50%; transform: translateX(-50%);
centers the tooltip horizontally.bottom: 100%; margin-bottom: 5px;
positions it just below the text. - Styling: Basic styling is applied for background color, text color, padding, and border-radius.
white-space: nowrap;
prevents the tooltip text from wrapping to multiple lines. - Transitions: The
opacity
andvisibility
properties are transitioned for a smooth fade-in effect. pointer-events: none;
: This is crucial to prevent the tooltip from blocking mouse events on the underlying element.z-index: 1;
: Ensures the tooltip appears above other content.
This improved version is more robust, flexible, and follows best practices for creating tooltips with CSS. You can easily customize the styling and positioning to fit your specific needs. Remember to include this CSS in your <style>
tag or in a separate CSS file linked to your HTML.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?