How can one animate the width of an element with width: auto when its content changes? The content changes dynamically, and the element's width should change accordingly with animation.
While CSS does not directly support animating auto values, there are two approaches to achieve this effect:
1. Max-Width/Max-Height Trick
.myspan { display: inline-block; font-size: 30px; background-color: #ddd; max-width: 500px; /* Set a sufficiently large max-width */ }
2. Script-Based Width Setting
$(document).ready(function() { $(".myspan").hover(function() { $(this).width($(this).find("span").outerWidth()); }, function() { $(this).width("auto"); }); });
Using the max-width/max-height trick, we can create a simple example where the element's width animates on hover:
.myspan { display: inline-block; font-size: 30px; background-color: #ddd; vertical-align: bottom; } .myspan::after { content: " <pre class="brush:php;toolbar:false"><link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" /> <span class="myspan">Hello!</span>
The above is the detailed content of How to Animate an Element\'s Width with CSS When Content Changes Dynamically?. For more information, please follow other related articles on the PHP Chinese website!