CSS Tooltips

CSS Tooltips are small messages displayed when a user hovers over an element. They provide additional information or context about the element.

Key Topics

Basic Tooltip

A basic tooltip can be created using the title attribute, but for advanced control, custom tooltips with CSS are often preferred.

<style>
        .tooltip {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }
        .tooltip .tooltiptext {
            visibility: hidden;
            width: 120px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 5px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
        }
        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
</style>
<div class="tooltip">
    Hover me
    <span class="tooltiptext">Tooltip text</span>
</div>

Explanation: The tooltip text appears above the element when hovered, transitioning smoothly using opacity.

Tooltip Positioning

Tooltips can be positioned at the top, bottom, left, or right of the element using CSS properties like top and left.

<style>
        .tooltip .tooltiptext-bottom {
            bottom: -50%;
            top: auto;
        }
        .tooltip .tooltiptext-left {
            left: -130%;
            transform: none;
        }
        .tooltip .tooltiptext-right {
            left: 130%;
            transform: none;
        }
</style>
<div class="tooltip">
    Hover me
    <span class="tooltiptext tooltiptext-bottom">Tooltip below</span>
</div>

Explanation: The tooltip's position is adjusted using CSS to display at the desired location relative to the element.

Tooltip Styling

Custom styling can be applied to tooltips to make them visually appealing. This includes changing colors, adding shadows, and more.

<style>
        .tooltip .tooltiptext {
            background-color: #333;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            padding: 10px;
        }
</style>
<div class="tooltip">
    Hover me
    <span class="tooltiptext">Styled Tooltip</span>
</div>

Explanation: The tooltip is styled with a dark background and subtle shadow for better visibility and design.

Key Takeaways

  • Basic Tooltips: Use title or custom tooltips for better control.
  • Positioning: Adjust tooltip placement using top, left, and related properties.
  • Styling: Enhance tooltips with custom colors, shadows, and animations for better user experience.
  • Transitions: Use opacity and transitions to create smooth effects.