Skip to content Skip to sidebar Skip to footer

Animate Element From Center Of View To Its Original Position

I'd like to create one animation to move the elements from the center of current view to the original positions. But CSS animation doesn't support toggling display property, so you

Solution 1:

It is possible to do this with pure CSS, but it is necessary to use the CSS variables property.

Here I have saved a working example..

I am also adding a working snippet of code below so you can test it.

:root {
  --target-offset: 0px;
}

.target-offset {
  --target-offset: 400px;
}

.fixed-center {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.instruction-target {
  position: relative;
}
.highlight-box {
  width: 100px;
  height: 20px;
  font-weight: bold;
  font-size: 2em;
  border: solid 5px red;
  display: inline-block;
}

.float-highlight-box {
  position: fixed;
  top: 0;
  left: var(--target-offset);
  animation-name: moving-to-target;
  animation-duration: 3s;
  opacity: 1;
}

@keyframes moving-to-target {
  /* animate from: center of current view */
  from {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    position: fixed;
    opacity: 1;
  }
  /* animate to: its original position */
  to {
    top: 0px;
    left: var(--target-offset);
    opacity: 0;
  }
}
<div style="width: 100%; min-height: 400px;border: solid 1px blue">
  <a class="fixed-center">CENTER</a>
  <button class="instruction-target">
    Test1
    <span class="highlight-box float-highlight-box"></span>
  </button>
  <button class="instruction-target target-offset" style="margin-left: var(--target-offset)">
    Test2
    <span class="highlight-box float-highlight-box"></span>
  </button>
</div>

Post a Comment for "Animate Element From Center Of View To Its Original Position"