I know it is possible to create a custom "tooltip" with the :hover:after selectors and to align this tooltip relative to the original element by marking the original element as position:relative and the tooltip as absolute.
HTML:
test
<span custom-tooltip="testing a custom tooltip" class="tooltip">
test
</span>
test
CSS:
.tooltip {
position: relative;
}
.tooltip:hover:after {
content: attr(custom-tooltip);
position: absolute;
background: black;
color: white;
}
However, I must use absolute values to position or size this :after element
top: 30px;
left: -30px;
width: 300px;
What if I want to make the element as wide as it needs to be (Percentages are relative to the parent element creating a large vertical box so I can’t tell it to go width: 100%)
And centered under the parent (left: -50% results in it being moved 50% of the parent to the left, not centered)
Is this possible without javascript? (If not, are there some magic selectors or functions to get the width of this or that and calc() the correct values?
You can force the tooltip onto a single line by using
white-space:nowrap. I don’t know of any way to center the tooltip without forcing a specific width on both the tooltip and the item the tooltip applies to. Here’s a general-purpose example (without centering):And the CSS:
Note that I’m using
:beforeinstead of:after. If you want to center the tooltip and are able to define a fixed width, you can use this CSS instead:Here, the item is given a fixed width equal to the width of the tooltip then negative left/right margins to collapse it back down to the desired size. Note the addition of
display:inline-blockandtext-align:center.This technique isn’t practical for inline tooltips, but works well for buttons and “call to action” links.