Ryan Peschel
Ryan Peschel

Reputation: 11996

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?

Upvotes: 4

Views: 1014

Answers (2)

Dan Knights
Dan Knights

Reputation: 8368

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>

Upvotes: 4

vbuzze
vbuzze

Reputation: 940

You can offset it absolutely relative to a parent who is 0x0 and positioned relatively, and further make the parent move with your mouse.

<!DOCTYPE html>
<html>
   <head>
      <style>
         .origin {
            position: relative;
            width: 0px;
            height: 0px;
         } 

         .circle {
            position: absolute;
            top: -10px;
            right: -10px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 3px solid red;
         }
      </style>
   </head>
   <body>

      <div class="origin">
         <div class="circle"/>
      </div>

   </body>
</html>

See more details: https://www.w3schools.com/css/css_positioning.asp

Upvotes: 1

Related Questions