Home > Blockchain >  How can I transition an element between a relative position to an absolute position?
How can I transition an element between a relative position to an absolute position?

Time:01-16

I'm working on a portfolio site and I had this cool idea that the landing page will have the name in the middle and then when I select a route the page will turn into a navbar.

The problem is, in order to do this I either have to position the navbar items absolutely, which I don't want to do, or I need to center the name in the middle of the screen relative to its original position, which is not desirable either.

This is how it looks now

I'm using Vue with Tailwind, but a vanilla HTML solution would help.

This is my code:

<template>
  <header
    
    :
  >
    <div
      
      :
    >
      <router-link to="/" :>
        <div
          
          :
        >
          Aby
        </div>
        <div
          
          :
        >
          Isakov
        </div>
      </router-link>
      <router-link to="/other">click</router-link>
    </div>
  </header>
</template>

I tried to position the navbar items absolutely, but this caused problems with making the component responsive.

CodePudding user response:

You need to take some steps to apply a transition that changes the 'position' css property. Here is the function that does it with a relative positioned element:

function positionTransition(element) {
    var rectBefore = element.getBoundingClientRect(); //get old coordinates
    
    //change positioning:
    element.style.position = "absolute";
    element.style.left = "50vw";
    element.style.top = "50vh";
    
    var rectAfter = element.getBoundingClientRect(); //get new coordinates
    
    //calculate the difference:
    var xDiff = -(rectAfter.x - rectBefore.x);
    var yDiff = -(rectAfter.y - rectBefore.y);
    
    //translate back, so that the absolute positioned element seems to be in the old place:
    element.style.transform = "translate("   xDiff   "px, "   yDiff   "px)";
    
    //finally, make the transition, which works because it remains in position: absolute
    setTimeout(function() { //without the timeout, transition is ignored
        element.style.transition = "transform 1000ms ease-in-out";
        element.style.transform = "";
    }, 10);
}

I know what you're thinking, but don't worry. The change in position and translate back is instantaneous, there is no flicker!

CodePudding user response:

Unfortunately, this can't be achieved for time being according the docs.


Reference

1. w3 docs

Animatable: no

2. mozilla docs

Animation type: discrete

  • Related