jeanmarc jeanmarc - 4 months ago 6
HTML Question

Width transition of text with CSS not working

Thanks in advance, guys.

I have a div where I want to show the name of a person.

In normal state you only see the person's first name, and when you mouseover, the last name appears on the right of the first name, with its width expanding from 0 to normal width. All this text is aligned to the right.

I tried many ways to do it, if I apply the transition to the last name span it doesn't even show it, I also tried with max-width (as a guy does here: http://jsfiddle.net/qP5fW/87/ ) but it doesn't work.
So I made a wrapper div, used width instead of max-width and now it works, only it doesn't show the transition at all.

I suspect the problem is with the "auto" property but if anyone knows how to make the transition work, I would be very grateful.

Here's my fiddle: https://jsfiddle.net/drywrsy6/

<div class="name">
<span class="first">John</span>
<div class="last-wrapper">
<span class="last">Doe</span>
</div>
</div>


CSS

.name {
border: 1px solid lightgrey;
margin: 10px auto 0px auto;
padding: 5px;
width: 300px;
font-size: 2em;
text-align: right;
overflow: hidden;
white-space: nowrap;
}

.first {
font-style: italic;
}

.last-wrapper {
display: inline-block;
vertical-align: bottom;
overflow: hidden;
width: 0;
transition: all 1s;
}

.last {
color: red;
}

.name:hover .last-wrapper {
width: auto;
}


Again, any help appreciated. Thanks in advance!

Answer

You can use max-width, as it won't work with width: auto.

Just make sure the max-width value is big enough to accommodate the widest text, or you need a script calculating this on load.

.name {
  border: 1px solid lightgrey;
  margin: 10px auto 0px auto;
  padding: 5px;
  width: 300px;
  font-size: 2em;
  text-align: right;
  overflow: hidden;
  white-space: nowrap;
}

.first {
  font-style: italic;
}

.last-wrapper {
  display: inline-block;
  vertical-align: bottom;
  overflow: hidden;
  max-width: 0;
  transition: all 1s;
}

.last {
  color: red;
}

.name:hover .last-wrapper {
  max-width: 100px;
}
<div class="name">
  <span class="first">John</span>
  <div class="last-wrapper">
    <span class="last">Doe</span>
  </div>
</div>

Comments