我有一个 div,我想在其中显示一个人的名字。
我只想在正常状态下显示该人的名字。当您将鼠标悬停时,姓氏应出现在名字的右侧,其宽度从 0 扩展到正常宽度。所有这些文本都右对齐。
如果我将过渡应用于姓氏范围,它甚至不会显示。
我也尝试过 max-width (就像一个人在这里所做的那样: http://jsfiddle.net/qP5fW/87/ )但它不起作用。
所以我制作了一个包装 div,使用 width 而不是 max-width,现在它可以工作了,只是它根本不显示过渡。
我怀疑问题出在“auto”属性上,但如果有人知道如何进行转换,我将非常感激。
这是我的 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;
}
最佳答案
您可以使用max-width
,因为它不能与width: auto
一起使用。
只需确保 max-width
值足够大以容纳最宽的文本,否则您需要一个脚本在加载时计算此值。
由于 max-width
会比某些内容更宽,因此可以设置较短的反向过渡持续时间,以使其在较宽的文本上看起来更好。
.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>
根据评论更新
请注意,如 SimoAmi写道,“...当缩小时,反转动画,如果您的文本为 100 像素并且指定最大宽度为 1000 像素,则大部分动画时间都花在缩小空白 900 像素差异上”
解决这个问题的一种方法是详细说明其 transition's timing function
,其中自定义三次贝塞尔曲线
可能是一种选择。
关于html - CSS 文本的宽度过渡不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38706515/