Home > Software design >  Animate a div to increase width and height, expanding outwards in all directions
Animate a div to increase width and height, expanding outwards in all directions

Time:11-06

I have a circle div, and I want to make it so when it is clicked it expands outwards in all directions and then comes back in. The trouble is, because position is defined by the top-left corner, the circle gets bigger, but expands only down and to the right, which creates a weird looking effect.

document.getElementById("circle").onclick = function(e){
  document.getElementById("circle").classList.add("animate")
  document.addEventListener("animationend", function(){
  document.getElementById("circle").classList.remove("animate")
  });
};
#circle{
  width: 20px;
  height: 20px;
  background-color: black;
  position: absolute;
  top: 50%;
  left: 50%;
  border-radius: 50%;
  
  
}

.animate{
  animation-name: expand;
  animation-fill-mode: forwards;
  animation-duration: 1s;
  
}
@keyframes expand{
  0%{width: 20px; height: 20px;}
  50%{width: 50px; height: 50px;}
  100%{width: 20px; height: 20px;}
}
<div id = "circle"><div>

I would really prefer it it would expand at all sides, like if position were defined from the center and you just increased the radius. Is there any way to get this effect?

CodePudding user response:

Use clip-path

document.getElementById("circle").onclick = function(e){
  document.getElementById("circle").classList.add("animate")
  document.addEventListener("transitionend", function(){
  document.getElementById("circle").classList.remove("animate")
  });
};
#circle{
  width: 100px;
  height: 100px;
  background-color: black;
  position: absolute;
  inset:0;
  margin: auto;
  border-radius: 50%;
  clip-path: circle(20%);
  transition: .5s;
}

#circle.animate{
  clip-path: circle(50%)
}
<div id = "circle"><div>

  • Related