My objective is to display a styled tooltip in an HTML document.
To achieve this, I have written the following code:
.word-with-tooltip{
position:relative;
}
.tooltip{
position:absolute;
bottom:1.5em;
right:0;
height:100px;
width:200px;
display:none;
border-style:solid;
border-width:1px;
border-color:gray;
background-color:#dddddd;
text-align:left;
}
.word-with-tooltip:hover .tooltip{
display:block;
}
<div style="height:200px"></div>
<div>
<span class="word-with-tooltip">
Left Car
<div class="tooltip">A vehicle with four wheels</div>
</span>
</div>
<div style="text-align:center;">
<span class="word-with-tooltip">
Centered Car
<div class="tooltip">A vehicle with four wheels</div>
</span>
</div>
<div style="text-align:right;">
<span class="word-with-tooltip">
Right Car
<div class="tooltip">A vehicle with four wheels</div>
</span>
</div>
<div style="height:200px"></div>
Essentially, this code functions as intended by displaying a nicely formatted tooltip when hovering over a word with the mouse: https://i.sstatic.net/LMDjk.png
However, there is an issue where the tooltip gets cut off when it's positioned too far to the left:
https://i.sstatic.net/lbIPn.png
A potential solution would be to adjust the CSS property from right
to left
based on the location of the tooltip relative to the screen. Since the position of the tooltip can vary within a large text, this adjustment is necessary for proper display.
Inquiry: Is it feasible (and how) to ...
- set the CSS property
left:0
if the word is located in the left half of the screen? - set the CSS property
right:0
if the word is placed in the right half of the screen? - set the CSS property
top:1em
if the word is situated in the upper half of the screen? - set the CSS property
bottom:1em
if the word is found in the lower half of the screen?