How can I transition width of content with width: auto?
As I commented, one can't animate auto
(yet), so either use the max-width
/max-height
trick, or, if you need it to be more exact, set the width using a script.
With the max-width
/max-height
trick, give it a value big enough to accommodate the widest.
Stack snippet
.myspan {
display: inline-block;
font-size: 30px;
background-color: #ddd;
vertical-align: bottom;
}
.myspan::after {
content: " \00a0\f12a ";
font-family: ionicons;
font-size: 80%;
display: inline-block;
max-width: 0;
transition: max-width .6s;
vertical-align: bottom;
overflow: hidden;
}
.myspan:hover::after {
max-width: 80px;
transition: max-width 1s;
}
<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" />
<span class="myspan">Hello!</span>
Luke Taylor
An 19-year-old creative developer/designer studying at Tufts University. I’m currently focused on web technologies. Find me on GitHub, Dribbble or on my website.
Updated on January 10, 2022Comments
-
Luke Taylor over 2 years
I have an element whose width I'd like to animate when its contents change. It has
width: auto
, and this never changes. I've seen this trick, but that's for transitioning between two values and one is set. I'm not manipulating the values at all, only the content, and I'd like my element's size to change with animation. Is this at all possible in CSS?Here's a simplified version of my code:
.myspan { background-color: #ddd; } .myspan:hover::after { content: "\00a0\f12a"; font-family: Ionicons; font-size: 80%; }
<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet"/> <html> <body> <span class="myspan">Hello!</span> </body> </html>
I'd like the changing size to animate when the user hovers over the element.
-
Luke Taylor almost 8 yearsRight, do it on the pseudo element. I thought you were suggesting putting it on the main element, that's why I was confused ;)
-
Asons almost 8 years@LukeTaylor If your close icon has a predefined width, you can just use width instead,and give the pseudo the final width icon included
-
Luke Taylor almost 8 yearsSorry, but can you give me a bit more help? Combining
overflow: hidden
withdisplay: inline-block
makes the ionicon disappear. -
Asons almost 8 years@LukeTaylor Updated my answer
-
Luke Taylor almost 8 yearsHmm, it seems to work when I tried to create a MCVE demonstrating the issue. I'll come back if I can't solve.
-
Luke Taylor almost 8 yearsThe issue was caused by my (silly) use of
line-height: 0
as a temporary hack to fix layout. Obviously, this would hide the icon when usingoverflow: hidden;
. Sorry for the trouble.