Keep tooltip position on screen
I have this codepen with a basic CSS tooltip made with pseudo elements but there are few problems when the tooltip exceed the size of the screen. Is there any way to use CSS only to keep the tooltip fully on screen? If no, how can I get the position and size of pseudo elements and calculate a position inside the screen of device?
https://codepen.io/Andk2828/pen/bGKGWRx
7 Replies
I don't think you can achieve that with CSS alone since you cannot predict the position of the tooltip element or the size of the window.
You would have to use JavaScript to dynamically calculate these variables, and use them to adjust the position of both pseudo elements (the content itself and the arrow).
next problem is (i think), you can not get the position of a pseudo element in js
If you are interested (I suggest you try yourself first) I made a version of how this could be done, although it's very rough and with hard coded values, but it works. In addition to the JavaScript code, I made some changes on the CSS as well as I needed to move around the before and after pseudo elements separately.
https://codepen.io/D10f/pen/rNKNzEb
You can, use the
window.getComputedStyle
method: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle#use_with_pseudo-elementsyea, i know. thought it would only be possible with bounding client rect. but you did a smart thing. bravo
you combined the 2
The only smart thing I did was google it up 😂
haha, that is a skill too
I tried also with getComputedStyle for pseudo elements but I am not sure if the measures are right. At width 855px the tooltip is still off screen.