Prevent CSS tooltip from going out of page/window

Paul M picture Paul M · Jun 21, 2018 · Viewed 21.4k times · Source

I have a CSS only tooltip which loads a span as a tooltip when you hover the link. However this is positioned with CSS but if the link is near to the top of a page or side then the tooltip goes off the side/top of the page.

Is there a way with css to make this change or will I have to rely on JS? I have started to try to put something together with jQuery but would rather use CSS if possible.

JS fiddle at https://jsfiddle.net/gtoprh21/12/

Snippet:

Answer

Takit Isy picture Takit Isy · Jun 27, 2018

Unfortunately, if you want to keep your tooltip good positioning, it isn't possible using only CSS.

Script solutions

But, as you're already using some script, I suggest you this solution:

  • Use position: absolute to position the .ktooltiptext accordingly to .ref,
  • Use the .getBoundingClientRect() method to easily get the position and size of the tooltip,
  • Apply some correction if out of the window,
  • Also made some modifications in CSS.

Snippet with only native JavaScript (avoiding jQuery, document will be lighter.)