CSS only tooltip, horizontally centered
Yet another solution for CSS only tooltips. But this one automatically horizontally align them using the translate property.
HTML
<div href="#" class="tooltip-oneline" data-tooltip="Content of the tooltip">Hover me ! (one line, width auto)</div>
<br>
<br>
<br>
<br>
<br>
<a href="#" class="tooltip-multiline" data-tooltip="Content of the tooltip Content of the tooltip Content of the tooltip">Hover me ! (multi line, fixed width)</a>
SCSS
body {
padding: 5em;
}
[data-tooltip] {
position: relative;
text-align: center;
&:after {
content: attr(data-tooltip);
display: block;
position: absolute;
padding: .25em .5em;
bottom: 100%;
margin-bottom: 0;
left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
transition: all .25s;
background: black;
opacity: 0;
color: #fff;
border-radius: @radius;
text-align: center;
font-size: 1rem;
white-space: nowrap;
pointer-events: none; // Avoid hovering tooltip
}
&:hover:after {
opacity: 1;
margin-bottom: 10px;
}
}
.tooltip-multiline {
&:after {
width: 150px;
white-space: normal;
}
}
JavaScript
// Example 1 : width auto, but can't have multi lines
// Example 2 : can have multi line, but width should be manually set