senty senty - 1 month ago 6
CSS Question

Transition on Stretching Div

I have a div with some content in it, and I am showing a button with jQuery. I want to fade it in thus I used:

setTimeout(function() {
jQuery('#button').css('opacity', 1);
}, 100);


First, on html, I have set the button's html to
display:none; opacity: 0
I have achieved showing/hiding button, however when it shows, it's making the div stretch instantly. Instead, I want the parent div to expand with transition.

I have created a Fiddle: https://jsfiddle.net/atg5m6ym/7450/ . In this example, when I press the trigger button, I want the button to fade in as well as applying transition on the parent div.

Answer

For optimal performance, when using transitions and animations in CSS, you should stick to opacity and transform instead of display: none; and width/height.

Will quote the comment I stated above:

The way you designed this is not ideal, you should not be using display: none; in transitions or animations. This will cause redrawing in your browser, and you cannot transition properties with binary settings, display just switches between states (ex: none/block), not between values like opacity does.


What you could do is separate your content, sharing the same background color to simulate it is the same container.

Then use transform and the scale() function.

Code Snippet:

jQuery('#trigger').click(function() {
  jQuery('.bottom-content').addClass('open');
})
.top-content,
.bottom-content {
  background-color: lightblue;
}
.bottom-content {
  transform: scaleY(0);
  transition: transform 250ms ease-in;
  transform-origin: top;
}
.bottom-content.open {
  transform: scaleY(1);
}
.bottom-content.open #otherButton {
  opacity: 1;
}
#otherButton {
  margin-top: 20px;
  opacity: 0;
  transition: opacity 10s;
  transition-delay: 250ms;
  /* Separated for clarity purposes, wait for parent transition to end before starting this one*/
}
<script src="https://www.addressfinder.co.nz/assets/v2/widget.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="content">
    <section class="top-content">
      <button id="trigger">
        Trigger
      </button>
      <br />Lalala La
      <br />Lalala La
      <br />Lalala La
      <br />
    </section>
    <section class="bottom-content">
      <button id="otherButton">
        Test Btn
      </button>
    </section>
  </div>
</div>

Comments