How to set div for extension with transition to change text

I want to easily expand my div (in a cool way) when the text inside it changes:

CSS transition: all 2s ease; works great for changing colors, manually setting widths, etc. (as you can try in jsfiddle - click the button to switch the width). but when the inner text of the div changes, the div just jumps to the new width without any transition.

How can I make the transition work when the inner text changes?

Thanks!

+4
source share
4 answers

Since the default width of the div will be auto (100%), it cannot go from auto to a numeric value.

+3
source

You can add below css to your div where the inner text of the div changes

 div {-webkit-transition: width 2s; /* For Safari 3.1 to 6.0 */ transition: width 2s;} 
0
source

Hi abagshaw try this script to solve your problem.

 var big = false; $('#content').on('click', function(e) { if(!big) { $( this).animate({ width: "600px" }, 500 ); this.innerHTML = "MORETEXTMORETEXTMORETEXTMORETEXTMORETEXTMORETEXTMORETEXT"; big = true; } else { $( this).animate({ width: "200px" }, 500 ); this.innerHTML = "LESSTEXTLESSTEXT"; big = false; } }); 
 .ui.transitioning.button{ transition:all 0.5s ease-in-out;-webkit-transition:all 0.5s ease-in-out; width:200px; } 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.0.7/semantic.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="ui transitioning teal button" id="content">LESSTEXTLESSTEXT</div> 
0
source

I do not think that dynamically changing the width of an element depending on its content is possible, since there is no transition for the content. The content of the element changes instantly, and the width does not get a numerical value in your case - but it is customizable.

A solution that can sometimes be applied: using a function to roughly calculate the width of the text so that you can set the numerical width for your element when changing . >.

Here is a simple one 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; } 

Compare the usage example .

0
source

All Articles