Skip to content
Advertisement

How to set the origin for a div?

Let’s say I have a div that follows the mouse cursor on my screen. This is done by handling the document mousemove event and setting its left and top position based on the event data.

For this example let’s say it has a width and height of 10.

It is desired for it to always be centered on the cursor. To make this happen the left and top need to be horizontally offset by half of div’s width and vertically offset by half of the div’s height. This allows it to be perfectly centered on the mouse cursor.

document.querySelector(".circle").style.left = e.x - (width / 2)

However, this is done in many places in the application and it seems cumbersome. Is it possible to instead set the origin such that when I set the left and top properties, I do not need to offset by half the width and height, since the origin would be at the center of the div?

The only thing I could find was the transform-origin property, but this seems to only apply to the transform CSS properties, and not properties like left, margin-left, etc.

Can this be done?

Advertisement

Answer

You could use:

transform: translate(-50%, -50%);

This calculates the percentage from the width and height of the element itself.

Example snippet:

const move = document.getElementById("move")
const mouseMoveHandler = e => {
  move.style.left = e.pageX + 'px';
  move.style.top = e.pageY + 'px';
}

window.addEventListener('mousemove', mouseMoveHandler)
#move {
  position: absolute;
  transform: translate(-50%, -50%);
}
<div id="move">I follow the cursor</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement