Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set div to expand with transition on text change

Tags:

html

css

I want to seamlessly expand my div (in a non-jarring way) when the text inside it changes:

The CSS transition: all 2s ease; is working great for colour changes, manually setting width, etc (as you can try out in the jsfiddle - click button to toggle width). but when the inner text of the div is changed the div just jumps to the new width without any transition.

How can I get the transition working when the inner text changes?

Thanks!

like image 799
abagshaw Avatar asked Aug 01 '15 02:08

abagshaw


2 Answers

Because the default width of the div will be auto (100%), it can't transition from auto to a numerical value.

like image 150
Mark Eriksson Avatar answered Jan 04 '23 02:01

Mark Eriksson


I don't think dynamically changing a width of an element depending on its content is possible, as there is no transition for content. The content of an element changes instantly and the width does not get a numerical value in your case - but adjusts.

A solution that can be sometimes applicable: Using a function to roughly calculate your text's width so that you'll be able to set a numerical width for your element on change.

Here's a simple one that I made.

function getTextWidth(text, css) {
    var e = $('<span></span>'); // dummy element
    e.css(css); // set properties
    e.text(text); // set test
    var width = e.appendTo($('body')).width(); // append and get width
    e.remove(); // remove from DOM
    return width;
}

Put together an example of usage.

like image 40
Guy Waldman Avatar answered Jan 04 '23 03:01

Guy Waldman