How is the CSS transition height of the P tag when the text is updated?

I have a paragraph tag on a site where I replace the content when a button is clicked (using Javascript) (i.e. replace quote # 1 with quote # 2). I'm not just expanding the text, sometimes the new text can be smaller than the current text, sometimes more.

In some cases, the text goes from a short to a longer amount, which causes quite a jerky movement on the site, since the tag <p>

instantly increases its height.

I thought by adding that a css transition from 2s might fix it, but it has no effect:

p.my-text {
  transition: 2s;
}

      

Is there a way to smoothly transition the height of the tag <p>

when the text is updated?

+3


source to share


2 answers


You cannot use a transition to height: auto;

, but instead you can use a transition between the given one max-height

(for example 0

) and the other is max-height

larger than expected. See https://codepen.io/LFeh/pen/ICkwe



+2


source


You can add a value max-height

to create a transition.

Take a look at this sample code.



var paragraph;
(() => {
	paragraph = document.getElementById('paragraph');
  paragraph.style.maxHeight = paragraph.scrollHeight +  "px";
	setInterval(() => {
  
  	paragraph.innerHTML = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus porttitor nisl sit amet turpis euismod, sit amet vulputate sem mollis. Duis vitae scelerisque magna, et varius neque. Suspendisse at velit in urna tincidunt pellentesque feugiat non erat. Etiam malesuada sapien sapien, sed finibus orci rhoncus sed. Morbi ultrices scelerisque malesuada. Phasellus non dictum ipsum, sed malesuada lacus. Cras dignissim, lectus vel volutpat vulputate, felis ligula molestie velit, at tempor risus eros et orci. Ut malesuada, libero sit amet imperdiet volutpat, tellus orci tempus enim, in luctus diam mi a enim. Phasellus arcu urna, semper sit amet lobortis non, tempus eget felis. Donec ullamcorper nibh feugiat, porttitor mauris ac, imperdiet mi. Nam lectus felis, efficitur quis turpis non, dignissim feugiat purus.";
  
  	paragraph.style.maxHeight = paragraph.scrollHeight +  "px";
  }, 1000);
	
})();
      

#paragraph {
  background-color: #eeeeee;
  transition: max-height 2s;
  overflow:hidden;
}
      

<p id="paragraph" >
lorem ipsum dolor
</p>
      

Run codeHide result


Note that you need to add overflow: hidden

+2


source







All Articles