To place a tooltip above a button, you need to know where the button is and how much space the tooltip occupies. A bounding box supplies both: it is the rectangle enclosing an element, described by its top-left corner (x, y) and its width and height. section 10.1 section 10.2.2
In JavaScript, element.getBoundingClientRect() returns that rectangle in viewport coordinates. Its left and top values locate the element; right and bottom locate its opposite edges. Width and height include padding and borders. With box-sizing: border-box, they match the element’s CSS width and height values. section 10.2
Center a tooltip above a button
Measure both elements. The button’s horizontal center is (buttonRect.left + buttonRect.right) / 2. Set the tooltip’s left position to that center minus tooltipRect.width / 2. Set its top position to buttonRect.top - tooltipRect.height - 8 for an 8px gap. On mouseenter, make the tooltip visible and calculate its position; on mouseleave, hide it. section 10.2.2
const button = document.getElementById('demoButton');
const tooltip = document.getElementById('tooltip');
function positionTooltip() {
const buttonRect = button.getBoundingClientRect(); #1
const tooltipRect = tooltip.getBoundingClientRect(); #1
const buttonCenterX = (buttonRect.left + #2
buttonRect.right) / 2; #2
tooltip.style.left = buttonCenterX - #3
tooltipRect.width / 2 + 'px'; #3
tooltip.style.top = buttonRect.top - #4
tooltipRect.height - 8 + 'px'; #4
}
button.addEventListener('mouseenter', () => { #5
tooltip.classList.add('visible'); #5
positionTooltip(); #5
}); #5
#5
button.addEventListener('mouseleave', () => { #6
tooltip.classList.remove('visible'); #6
}); #6
See the JavaScript that measures both bounding boxes and applies the calculated left and top positions. section 10.2.2









