skip to Main Content

Using tailwind css, I can center an absolutely positioned element in its relative container: <svg class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">...</svg>

Using tailwind css, I can make an absolutely positoined element spin: <svg class="absolute animate-spin">...</svg>

But when I try to center an absolutely positioned spinning element, <svg class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 animate-spin">...</svg>, instead of spinning, the non-spinning element just moves down and to the right at a -45deg angle.

What am I doing wrong?

3

Answers


  1. Chosen as BEST ANSWER

    '-translate-x-1/2 -translate-y-1/2' include an associated 'transform', but 'animate-spin' also includes a 'transform' within a @keyframe.

    It seems that these two transforms collide without being merged, possibly depending on the order of the keywords.

    My workaround: a wrapper element

    <div class="absolute left-1/2 right-1/2 -transform-x-1/2 -transform-y-1/2">
       <svg class="aninate-spin">...</svg>
    </div>
    
    

  2. As I understand, when you use both translation classes, i.e., -translate-x-1/2 and -translate-y-1/2 with the class animate-spin, it is very likely to cause this behavior.

    Solution: A solution approach would be to also use transform class along with the above 3 mentioned classes.

    Reason: By adding transform class, it ensures that the two translational classes are grouped for performing transformation rather than changing position.

    In this way, the element will have the properties of both center and spin as per your requirement.

    Login or Signup to reply.
  3. tailwind uses this css:

    animate-spin:   animation: spin 1s linear infinite;
    
    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
    

    and also

    -translate-x-1/2    transform: translateX(-50%);
    -translate-y-1/2    transform: translateY(-50%);
    

    Solution: I think this behavior is because spin and translate both manipulate transform property.
    so you can wrap the svg in a div and set position related classes to that div and for svg only use animation class:

    <div class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
       <svg class="animate-spin">...</svg>
    </div>  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search