brsastre
brsastre

Reputation: 35

CSS transition effect not working

I have created a "read more / read less" collapsable button with javascript, for the bio description of authors, on a wordpress site I am working on.

The collapsable is working fine, except that the transition css effect not working. I have tested this, and I think it is because when I uncollapse the text, i set the height to "auto", because obviously I don't know how long the text is going to be.

If I set the height to a number, the transition works. But I need to set to auto.

here is the fiddle: https://jsfiddle.net/brsastre/jo29pfm8/

p {
  height: 30px;
    overflow: hidden;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
p.uncollapsed {
  height: auto;
}

Upvotes: 0

Views: 46

Answers (3)

felixmosh
felixmosh

Reputation: 35603

You can't transition to height: auto, one of the coolest tricks is to animate max-height in order to get the same effect of height: auto.

Something like that:

var button = document.getElementById("button");
button.onclick = function() {
  var text = document.getElementById("text");
  text.classList.add("uncollapsed");
};
p {
  max-height: 30px;
  overflow: hidden;
  transition: max-height 0.5s ease;
}

p.uncollapsed {
  max-height: 100px;
}
<p id="text">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem obcaecati tenetur voluptates asperiores vero necessitatibus incidunt magni beatae debitis. Libero error, ab. Debitis odit, nulla blanditiis obcaecati assumenda eveniet. Nesciunt. Lorem
  ipsum dolor sit amet, consectetur adipisicing elit. Dolorem libero provident beatae qui minima iusto, corrupti quidem nam iste alias dicta? Cupiditate quidem neque dolores distinctio quam commodi inventore provident.
</p>
<button id="button">button</button>

Upvotes: 1

Mark
Mark

Reputation: 11

You can't animate to or from a dimension of "auto" (unfortunately). you should use the height to animate. here is the solution :

p {
  height: 30px;
    overflow: hidden;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
p.uncollapsed {
  height: 80px;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

Upvotes: 1

Nir Ben-Yair
Nir Ben-Yair

Reputation: 1606

This won't work because of height: auto. Try this:

p {
   height: 30px;
   overflow: hidden;
   -webkit-transition: all 0.5s ease;
   -moz-transition: all 0.5s ease;
   -o-transition: all 0.5s ease;
   transition: all 0.5s ease;
}

p.uncollapsed {
  height: 100px;
}

Upvotes: 0

Related Questions