Luke Taylor Luke Taylor - 4 months ago 13
CSS Question

CSS transition auto width

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: " Hello!"
}

<html>
<body>
<span class="myspan">Hello!</span>
</body>
</html>





I'd like the changing size to animate when the user hovers over the element.

Answer

As I commented, use the "max-width"/"max-height" trick.

Give it a value that is big enough to accommodate the widest.

.myspan {
  display: inline-block;
  font-size: 30px;
  background-color: #ddd;
  vertical-align: bottom;
}
.myspan::after {
  content: "  Hello";
  display: inline-block;
  max-width: 0;
  transition: all 1s;
  vertical-align: bottom;
  overflow: hidden;
}
.myspan:hover::after {
  max-width: 80px;
  transition: all 1s;
}
<html>

<body>
  <span class="myspan">Hello!</span>
</body>

</html>

Comments