I want to center a speech bubble-esque tooltip element under a link. Here is my current code to do so:
.tooltip-container {
position: relative;
display: inline-block;
}
.tooltip {
position: absolute;
z-index: 1;
background-color: #555;
color: #fff;
padding: 4px 8px;
border-radius: 4px;
white-space: nowrap;
top: 100%;
left: 50%;
transform: translateX(-50%);
margin-top: 0.5em;
}
.tooltip:before {
content: '';
position: absolute;
top: -5px;
left: 50%;
transform: translateX(-50%) rotate(45deg);
width: 10px;
height: 10px;
background-color: #555;
z-index: -1;
}
Up ahead is a
<a href="#">
Button text
</a>
<div class="tooltip-container">
<div class="tooltip">
Tooltip explanation of button
</div>
</div>
It looks like this
But I would like it to look like this
The only reason I made the .tooltip-container
div is to have a positioned ancestor for .tooltip
so that .tooltip
can be position: absolute
, but despite having that "anchor" in the page I can’t figure out a way to center the second child inside of the first one. My ideal HTML would only be:
<a href="#">
Button text
</a>
<div class="tooltip">
Tooltip explanation of button
</div>
and I only want to apply styling rules to these two elements, not their parent. How can I achieve this?
2
Answers
Just move
a
to.tooltip-container
In a far future you can use the new anchor positioning : https://drafts.csswg.org/css-anchor-position-1/#anchoring
No browser support for this actually but I leave the answer for the future
Until then, you can put the tooltip inside the link