Material design icons css rotation is not centered

Laker picture Laker · Mar 27, 2018 · Viewed 8.7k times · Source

I'm trying to make a loading spiner with icon from https://materialdesignicons.com/ but the icon doesn't just rotate, it also moves slightly from the center.

I have these styles:

@keyframes spin-animation {
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

.spin:before {
  display: block;
  transform-origin: center center;
  -webkit-backface-visibility: hidden;
  -webkit-animation: spin-animation 2s linear infinite;
  animation: spin-animation 2s linear infinite;
}

It's <i class="mdi mdi-something spin"> element. So it has added :before with content of the icon. This element sits in an absolutely positioned wrapper, with display: flex, horizontally and vertically centered.

The problem is that when the icon rotates, it doesn't rotate around its center. The axis moves by a little. The icon doesn't stay in one centered position, instead it moves slightly.

the icon doesn't just rotate, it also moves

I've tried:

  • Giving width and height to the i element
  • Giving width and height to the :before element
  • Moving the spiner animation from i to :before
  • Different styles which I've found on stackoverflow, e.g. transform-origin: center center;

The icon itself has the same x and y dimensions so it shouldn't be a problem. The dimensions change when it rotates, but I guess that's correct?

Answer

Miczi picture Miczi · Apr 8, 2019

Have a look at Gabriele Petrioli answer in this thread: https://stackoverflow.com/a/14859567/1374439 on how to implement spin with CSS3.

Based on his suggestion the below worked perfectly for me.

@keyframes spin {
    from {
        transform:rotate(0deg);
    }
    to {
        transform:rotate(360deg);
    }
}

.spin {
  animation-name: spin;
  animation-duration: 4000ms;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}