Width transition of text with CSS not working

2019-09-11 02:34发布

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

I want to only show the person's first name in the normal state. When you hover, the last name should appear on the right of the first name, with its width expanding from 0 to normal width. All this text is aligned to the right.

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/

HTML:

<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;
}

1条回答
The star\"
2楼-- · 2019-09-11 03:16

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.

As the max-width will be somewhat wider than some content, one can have a transition duration with shorter time on reverse, to make it look better on less wide text.

.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 0.3s;
}

.last {
  color: red;
}

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


Updated based on a comment

Do note, and as SimoAmi wrote, "...when shrinking, reversing the animation, if your text is 100px and you specify max-width of 1000px, much of the animation time is spent shrinking the blank 900px difference"

One way to deal with that is to elaborate with its transition's timing function, where a custom cubic-bezier curve could be one option.

查看更多
登录 后发表回答