user1088793
user1088793

Reputation: 653

How to optimise CSS3 transitions on DIV resize?

I have a large image within a div which I apply a resize transition to. Perhaps it is simply the speed of my computer, however, I am finding that there is a slight delay when actioned, and also the resize itself is not smooth. I have attached a fiddle with a simplified version of the code, and below. Thank you.

function myFunction() {
  var element = document.getElementById("myID");
  element.classList.toggle("div_clicked");
}
.div {
  height: 200px;
  width: 200px;
  transition: height 0.65s ease-in-out;
}

img {
  height: 100%;
}

.div_clicked {
  height: 50px;
  width: 50px;
  transition: height 0.65s ease-in-out;
}
<div id="myID" class="div">
  <img onClick="myFunction();" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />
</div>

http://jsfiddle.net/obd0yfun/

Upvotes: 2

Views: 211

Answers (1)

Smollet777
Smollet777

Reputation: 1646

It's more efficient to use transform in your case.

"Transitioning certain properties causes the browser to recalculating styles every frame. This is fairly expensive, and can lead to unnecessary re-paints. Transform offload the rendering to the GPU. In simple terms, this turns the element into an image during the transition, avoiding any style recalculations which greatly increases performance." read more

.div {
  height: 200px;
  width: 200px;
  transform-origin: top left; // default value is "center"
  -webkit-transform: scale(1);
  -moz-transform:    scale(1);
  -ms-transform:     scale(1);
  -o-transform:      scale(1);
  transform:         scale(1);
  transition: transform 0.65s ease-in-out;
}

img {
  height: 100%;
}

.div_clicked {
  transform-origin: top left; // default value is "center"
  -webkit-transform: scale(.25);
  -moz-transform:    scale(.25);
  -ms-transform:     scale(.25);
  -o-transform:      scale(.25);
  transform:         scale(.25);
  transition: transform 0.65s ease-in-out;
}
<div id="myID" class="div">
  <img onClick="myFunction();" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
</div>

<script>
  function myFunction() {
    var element = document.getElementById("myID");
    element.classList.toggle("div_clicked");
  }
</script>

Upvotes: 1

Related Questions