DEV Community

Marco
Marco

Posted on • Originally published at blog.disane.dev

Einfach und schnell Tooltips erstellen

Einfache Tooltips mit HTML/CSS mit minimalem JavaScript erstellen? ich zeig dir wie es geht 🪄


Du willst mal eben einen Tooltip in HTML/CSS erstellen und willst dabei nicht das Title-Attribut nutzten, sondern einen eigenen Tooltip erstellen? Das geht einfacher als du denkst und dafür brauchst du keine externe Bibliotheken.

Data-Attribut to the rescue ⛑️

Kernstück ist das Data-Attribut von HTML. Damit können wir nicht nur JavaScript Daten aus HTML übergeben, sondern auch an CSS übergeben und es dort nutzen. CSS bietet nämlich eine Möglichkeit an, dieses Attribut abzufischen und in CSS-Klassen zu verwenden. mit attr()können wir uns denn Inhalt nun schnappen und als content anzeigen.

attr() - CSS: Cascading Style Sheets | MDNPreview imageThe attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element’s originating element is returned.

Mit ein bisschen Styling und minimalem JavaScript kannst du so schöne und ansprechende Tooltips erzeugen, die auch zum Design deiner Website passen.

Der Code 👨🏼‍💻

Nehmen wir an, wir möchten einen Button mit einem Tooltip ausstatten. Generell kann man das mit dem title-Attribut machen, aber die sehen nicht schön aus und sind auch recht unflexibel was die Styling-Möglichkeiten angehen.

title - HTML: HyperText Markup Language | MDNPreview imageThe title global attribute contains text representing advisory information related to the element it belongs to.

In unserem Beispiel möchten wir einfach einen Button mit einem Tooltip generieren. Dieser sieht wie folgt aus:

<button class="tooltip" data-tooltip="This is a tooltip!">Hover over me</button>
Enter fullscreen mode Exit fullscreen mode

Und hier kommt das Data-Attributzum Tragen! Wir erzeugen damit ein neues Attribut data-tooltip. Diesen Wert des Attributes geben wir dann an CSS weiter:

/* Styles for the tooltip */
.tooltip {
    position: relative; /* Position relative to contain the tooltip */
    cursor: pointer; /* Pointer cursor for better UX */
}

/* Hide the tooltip by default */
.tooltip::after {
    content: attr(data-tooltip); /* Use the data-tooltip attribute value */
    position: absolute; /* Position the tooltip */
    background-color: #333; /* Dark background */
    color: #fff; /* White text */
    padding: 5px; /* Some padding */
    border-radius: 5px; /* Rounded corners */
    white-space: nowrap; /* Prevent line breaks */
    opacity: 0; /* Start hidden */
    visibility: hidden; /* Start hidden */
    transition: opacity 0.3s; /* Smooth transition */
}

/* Show the tooltip on hover */
.tooltip:hover::after {
    opacity: 1; /* Show the tooltip */
    visibility: visible; /* Make the tooltip visible */
}
Enter fullscreen mode Exit fullscreen mode

Wie du siehst, haben wir damit den Inhalt des Attributes an CSS übergeben und können damit recht geschmeidig den Inhalt nutzen und anzeigen.

content - CSS: Cascading Style Sheets | MDNPreview imageThe content CSS property replaces content with a generated value. It can be used to define what is rendered inside an element or pseudo-element. For elements, the content property specifies whether the element renders normally (normal or none) or is replaced with an image (and associated “alt” text). For pseudo-elements and margin boxes, content defines the content as images, text, both, or none, which determines whether the element renders at all.

Positionierung des Tooltips 📰

Nun möchten wir aber auch möglicherweise entscheiden können, wo der Tooltip angezeigt wird, ob oben unten oder links und rechts. Auch dafür können wir das Data-Attribut nutzen, in dem wir eigene Klassen dafür schreiben und den Tooltip entsprechend mit transform positionieren:

.tooltip[data-position="top"]::after {
    bottom: 100%; /* Position above the element */
    left: 50%; /* Center the tooltip */
    transform: translateX(-50%); /* Center the tooltip */
    margin-bottom: 10px; /* Space between tooltip and element */
}

.tooltip[data-position="bottom"]::after {
    top: 100%; /* Position below the element */
    left: 50%; /* Center the tooltip */
    transform: translateX(-50%); /* Center the tooltip */
    margin-top: 10px; /* Space between tooltip and element */
}

.tooltip[data-position="left"]::after {
    right: 100%; /* Position to the left of the element */
    top: 50%; /* Center the tooltip */
    transform: translateY(-50%); /* Center the tooltip */
    margin-right: 10px; /* Space between tooltip and element */
}

.tooltip[data-position="right"]::after {
    left: 100%; /* Position to the right of the element */
    top: 50%; /* Center the tooltip */
    transform: translateY(-50%); /* Center the tooltip */
    margin-left: 10px; /* Space between tooltip and element */
}
Enter fullscreen mode Exit fullscreen mode

transform - CSS: Cascading Style Sheets | MDNPreview imageThe transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.

Dynamische Positionen ⚗️

Damit der Tooltip nun nicht über die Viewport-Grenzen hinaus läuft, nutzen wir ein kleines JavaScript, was die Abstände zum Viewport ausrechnet und das passende data-positionsetzt:

document.addEventListener('DOMContentLoaded', function() {
    const tooltips = document.querySelectorAll('.tooltip');

    tooltips.forEach(tooltip => {
        tooltip.addEventListener('mouseover', () => {
            const tooltipRect = tooltip.getBoundingClientRect();
            const viewportWidth = window.innerWidth;
            const viewportHeight = window.innerHeight;
            const tooltipText = tooltip.getAttribute('data-tooltip');

            if (tooltipRect.top > 50) {
                tooltip.setAttribute('data-position', 'top');
            } else if (viewportHeight - tooltipRect.bottom > 50) {
                tooltip.setAttribute('data-position', 'bottom');
            } else if (tooltipRect.left > 50) {
                tooltip.setAttribute('data-position', 'left');
            } else if (viewportWidth - tooltipRect.right > 50) {
                tooltip.setAttribute('data-position', 'right');
            }
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

Das war's auch schon! Damit hast du nun deinen eigenen Tooltip mit (fast) purem CSS und HTML erstellt, den du sehr gut stylen und in deiner Website nutzen kannst.

Interaktives Beispiel 🛝


If you like my posts, it would be nice if you follow my Blog for more tech stuff.

Top comments (0)