I have been working on creating a CSS-only tooltip for a web application and so far I have managed to create some useful tooltips with different classes:
- tooltip-up
- tooltip-down
- tooltip-left
- tooltip-right
The distinguishing factors between them are the arrow direction and animation. For instance, the 'tooltip-right' class has the arrow pointing towards the left side and animates from left to right.
https://i.sstatic.net/qRapm.png
An issue arises when the tooltip contains a lot of text; the positioning differs for tooltip-left, tooltip-right, and tooltip-up due to the varying text length. Tooltip-down does not face any issues as everything naturally flows downwards by default.
https://i.sstatic.net/ZF84c.png
Hence, my question is whether it is feasible to precisely position the tooltip using only CSS. Or would JavaScript be necessary? If so, what approach would you recommend? Perhaps checking the text length in the tooltip and adding inline CSS for margins? As an example, I tried emulating Foundation Tooltips. We are utilizing Foundation but encountering compatibility issues with Angular.
Here's a snippet of code that I have implemented:
.tooltip-up,
.tooltip-down,
.tooltip-left,
.tooltip-right {
font-size: 12px;
position: absolute;
text-align: center!important;
visibility: hidden;
background-color: rgba($gray, 0.99);
color: #fff;
text-align: left;
border-radius: 3px;
width: 250px;
height: auto;
padding: 7px 10px;
z-index: 1;
opacity: 0;
box-shadow: 0 2px 5px 0 rgba($solid-black, 0.16), 0 2px 10px 0 rgba($solid-black, 0.12);
@include transition (.2s ease-in);
}
.tooltip-right {
top: -35%;
left: 135%;
transform: translateX(-15%);
margin-top: -10px;
&:after {
border-right: 7px solid rgba($gray, 0.99);
border-bottom: 7px solid transparent;
border-top: 7px solid transparent;
top: 50%;
content: " ";
height: 0;
left: -7px;
position: absolute;
width: 0;
transform: translateY(-50%);
}
}
Please note that there are four tooltip classes, so any solution should consider all positions (left, right, top). Thank you in advance for any advice or assistance provided.