Search code examples
csscss-animationscss-transitionscss-transforms

In a CSS transform, how to prevent shifting of scaled up element when scaling down


I want to use css to scale an element up on mouse hover and scaled it down again when the mouse leaves the element. The upper left edge should stay the same throughout all scaling.

The following code does almost what I want except that when I leave the mouse the element is shifted to the left before it is scaled down. I want the scaling down to start at the end position after the scaling up.

How can I accomplish this?

#test {
  height: 100px;
  width: 100px;
  background-color: lightgray;
  margin-left: 100px;
  margin-top: 100px;
  transition: transform 2s;
}  
#test:hover {
  transform: scale(2);
  transform-origin: left top;
}
<div id="test">Text</div>


Solution

  • The reason that is happening is that you declare transform-origin on the first time when you hover the element.

    Solution: Move transform-origin: left top; from #test:hover to #test.