CSS Only Tooltip


by Jeremy Caudle
code

Tooltips can be pretty handy and I've never given making my own a try. I tend to stick with the title attribute on elements and have never tried to build my own tooltips. I still need to tweak and improve the fade-out animation.

Can I make a tooltip appear for these words?This is a tooltip. Kind of.

View the code:

HTML and JS
<div class="code-block">

            <p>Can I make a tooltip appear for <span class="tooltip-words">these words?<span class="tooltip">This is a tooltip.</span></span> Kind of.</p>

        </div>
        
        <aside>
            <p>I decided to make this post after thinking about the article, <a href="https://css-tricks.com/long-hover/">Long Hover by Chris Coyier</a> over on <a href="https://css-tricks.com/">CSS Tricks</a>. I read it a couple of days ago and thought he shared some really helpful info.</p>
        </aside>
CSS
.code-block {
                background-image: linear-gradient(white, #efefef);
                min-height: 20vh;
                padding: 2rem;
                margin: 3rem auto;
                width: clamp(10em, 90vw, 60em);
                font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
                text-align: center;
            }

            .arrow-up, .arrow-down, .arrow-left, .arrow-right {
                width: 0;
                height: 0;
            }

            .tooltip-words {
                position: relative;
                text-decoration: underline;
                text-decoration-style: dotted;
            }

            .tooltip-words:hover .tooltip, .tooltip-words:focus .tooltip{
                transition-delay: 3s;
                opacity: 1;
                visibility: visible;
                width: auto;
                height: auto;
            }

            .tooltip {
                display: inline-block;
                position: absolute;
                width: 1px;
                height: 1px;
                padding: 1em;
                white-space: nowrap;
                visibility: hidden;
                transform: translateY(-125%);
                transition: 0.2s;
                opacity: 0;
                border-radius: .5em;
                background-color: rgba(0, 0, 0, .95);
                min-width: 20ch;
                color: fuchsia;
                text-align: center;
                font-weight: bold;
                left: -50%;
 }

            .tooltip::after {
                display: block;
                content: "";
                position: absolute;
                bottom: -1rem;
                left: calc(50% - 1rem);
                border-left: 1rem solid transparent;
                border-right: 1rem solid transparent;
                border-top: 1rem solid rgba(0, 0, 0, .95);
            }