CSS for Web Development

0% completed

Previous
Next
Create a CSS Tooltip Using Pseudo-Elements

Problem Statement

  • Create a tooltip that appears when a user hovers over an element.
  • Use CSS pseudo-elements (::before and/or ::after) to display the tooltip.
  • The tooltip should retrieve its text from a custom data attribute.
  • Include an arrow pointing toward the element.
  • Implement a smooth fade-in effect for the tooltip.

Solution

HTML

. . . .

Explanation:

  • Element Markup:

    • The tooltip is applied to a <span> with the class tooltip that holds a custom attribute data-tooltip containing the tooltip text.
  • Container Positioning:

    • The .tooltip class is given position: relative; so that its pseudo-elements (::before and ::after) can be positioned absolutely relative to it.
  • Tooltip Text (::after):

    • The ::after pseudo-element uses content: attr(data-tooltip); to fetch and display the tooltip text.
    • It is positioned above the element using bottom: 125%; and centered with left: 50% and transform: translateX(-50%);.
    • Additional styles (background, padding, border-radius, font-size) create a tooltip that looks visually appealing.
    • The tooltip is initially hidden with opacity: 0 and fades in smoothly with transition: opacity 0.3s ease;.
  • Tooltip Arrow (::before):

    • The ::before pseudo-element creates an arrow by setting borders. Only the bottom border is colored (#333), which gives the illusion of an arrow pointing downward toward the element.
    • It shares the same hidden-to-visible behavior as the tooltip text.
  • Hover Interaction:

    • When the .tooltip element is hovered, both pseudo-elements become visible (opacity: 1), causing the tooltip and arrow to appear with a smooth fade-in effect.

This solution successfully meets all the requirements by using only HTML and CSS to create a custom tooltip with an arrow and smooth transition effects.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next