javascripthtmlcssanchorpoint

How to move a div relative to its center(like an anchor point)?


When i drag a mouse over a div i want that div to resize after it's center like an anchor point but i don't know how.By default the "anchor point" it's set left-top

Here is an example :

var x = document.getElementById('mydiv');
x.onmouseover = function() {
  res_in(this.id);
};
x.onmouseout = function() {
  res_out(this.id);
};

function res_in(id) {
  document.getElementById(id).style.width = '70px';
  document.getElementById(id).style.height = '70px';
}

function res_out(id) {
  document.getElementById(id).style.width = '100px';
  document.getElementById(id).style.height = '100px';
}
.mydiv {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 100px;
  height: 100px;
  background-color: aqua;
  border-radius: 100px;
  transition: all 0.3s ease;
}
<div class="mydiv" id="mydiv">

</div>


Solution

  • The cleanest way to do this is using transform. You can use the scale function to resize. The default transform origin is in the middle, but you can change that if you want using css's transform-origin property, which works exactly like you describe it - it's an anchor point for the transform.

    Also, you don't need the JS that's in your example. Here's a working clean example:

    #mydiv {
      position: absolute;
      top: 50px;
      left: 50px;
      width: 100px;
      height: 100px;
      background-color: aqua;
      border-radius: 50%;
      transition: transform 0.3s ease;
      -webkit-transition: transform 0.3s ease;
      -moz-transition: transform 0.3s ease;
      -ms-transition: transform 0.3s ease;
      -o-transition: transform 0.3s ease;
      transform-origin: 50% 50%;
      -moz-transform-origin: 50% 50%;
      -ms-transform-origin: 50% 50%;
      -webkit-transform-origin: 50% 50%;
      -o-transform-origin: 50% 50%;
    }
    
    #mydiv:hover {
      background-color: red;
      transform: scale(0.7);
      -webkit-transform: scale(0.7);
      -ms-transform: scale(0.7);
      -moz-transform: scale(0.7);
      -o-transform: scale(0.7);
    }
    <div id="mydiv"></div>

    Read more: