Search code examples
htmlcsscss-animationscss-transforms

My div doesn't rotate at the center of the screen


It is my first question because I can't find solution for my easy problem (i guess). I don't know why my div is changing its position when it should rotate around itself. How can i resolve a problem of this type? I found some similar questions but about different location of their divs that don't point me to the answer.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: sans-serif;
  font-size: 30px;
  color: white;
  background-color: #333;
  overflow: hidden;
}

.square {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 400px;
  width: 400px;
  background-color: gold;
  border: 3px solid black;
  animation: square 4s ease-in-out .5s infinite;
  animation-direction: alternate;
  transition: transform 2s;
}

@keyframes square {
  from {
    top: 20%;
    background-color: aquamarine;
    transform: rotate(0deg);
  }
  to {
    top: 80%;
    background-color: sandybrown;
    transform: rotate(360deg);
  }
}
<div class="square"></div>


Solution

  • You need to add 3 things:

    1.) Add transform-origin: left top; to .square(because that "neutralizes your -50% top and left shifting)

    2.+3.) Add translate(-50%, -50%) to the two keyframe stages to make the object stay at the original transform setting, otherwise transform will switch to the default 0/0 values

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      font-family: sans-serif;
      font-size: 30px;
      color: white;
      background-color: #333;
      overflow: hidden;
    }
    
    .square {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      height: 400px;
      width: 400px;
      background-color: gold;
      border: 3px solid black;
      animation: square 4s ease-in-out .5s infinite;
      animation-direction: alternate;
      transition: transform 2s;
      transform-origin: left top;
    }
    
    @keyframes square {
      from {
        background-color: aquamarine;
        transform: rotate(0deg) translate(-50%, -50%);
      }
      to {
        background-color: sandybrown;
        transform: rotate(360deg) translate(-50%, -50%);
      }
    }
    <div class="square"></div>