使用css的attr()寫一個類似a標籤title的提示框

王铁柱6發表於2024-12-04
<!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 the data-tooltip attribute of the <span>. This makes the HTML cleaner and separates content from presentation.
  • attr(data-tooltip) in CSS: The content property of the ::after pseudo-element uses attr(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 and visibility 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.

相關文章