Reputation: 16726
I have a paragraph tag on a site in which I replace the contents of when a button is clicked (using Javascript) (ie: replace quote #1 with quote #2). I'm not simply expanding on the current text, sometimes the new text may be less than the current text, sometimes more.
In some cases, the text goes from a short about to a longer amount which causes a rather jerky movement on the site as the <p>
tag increases it's height instantly.
I thought by adding a css transition of 2s might fix it, but it has no effect:
p.my-text {
transition: 2s;
}
Is there is a way to transition the height of a <p>
tag smoothly when the text is updated?
Upvotes: 3
Views: 1069
Reputation: 673
You can add a max-height
value to create a transition on.
Take a look at this code sample.
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>
Note that you'll have to add overflow: hidden
Upvotes: 2
Reputation: 434
You cannot use a transition on a height: auto;
, but instead you can use a transition between a given max-height
(for instance 0
) and another max-height
bigger than the one expected. See https://codepen.io/LFeh/pen/ICkwe
Upvotes: 2