Skip to content
Advertisement

Animate two items moving away from each other until hitting container outline

For an intro animation, I want to animate two elements away from each other based on the outer container width to make it work responsive. Absolute positioning didn’t worked for me because initialy the two items has to touch each other or have a constant, fixed distance between them.

Here is a representation of the animation:

body {
background: #707070;
  text-align: center;
}

.content {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #f7f7f7;
}

.animated .content {
  justify-content: space-between;
}
<section class="intro">
  <h2>1. before animation</h2>
  <div class="content">
    <svg width="100" height="100">
      <rect width="100" height="100" fill="blue" />
    </svg>

    <svg width="50" height="50">
      <rect width="50" height="50" fill="green" />
    </svg>
 </div>
</section>

<section class="intro animated">
    <h2>2. after animation</h2>
    <div class="content">
      <svg width="100" height="100">
        <rect width="100" height="100" fill="blue" />
      </svg>

      <svg width="50" height="50">
        <rect width="50" height="50" fill="green" />
      </svg>
   </div>
</section>

<section class="intro animated">
    <h2>3. custom container size</h2>
  <div class="content" style="width: 80%;">
    <svg width="100" height="100">
      <rect width="100" height="100" fill="blue" />
    </svg>

    <svg width="50" height="50">
      <rect width="50" height="50" fill="green" />
    </svg>
 </div>
</section>

Advertisement

Answer

I’ve just added a div in the middle of SVGs, when you click on Container I will add animated class to the container. in CSS I will change dummy flex to auto

document.getElementById("container").addEventListener("click", function() {
  this.classList.add('animated');
});
body {
  background: #707070;
  text-align: center;
}

.content {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #f7f7f7;
}

.content.animated .dummy {
  flex: auto;
}

.dummy {
  flex: 0;
  transition: flex 1s;
}
<section class="intro">
  <h2>Click on container</h2>
  <div id="container" class="content">
    <svg width="100" height="100">
      <rect width="100" height="100" fill="blue" />
    </svg>

    <div class="dummy"></div>

    <svg width="50" height="50">
      <rect width="50" height="50" fill="green" />
    </svg>
  </div>
</section>

</section>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement