CSS过渡忽略宽度

10
我有一个标签,它显示为块状。在页面加载时,通过CSS动画将其宽度从零增加到包含div的一些百分比(该fiddle包含MWE,但此div中有多个链接,每个链接都有不同的宽度)。当悬停时,我希望它能改变颜色、背景颜色,并使用CSS过渡扩展到div的100%。颜色和背景颜色部分已经可以工作,但似乎忽略了宽度过渡。
代码片段:

.home-bar {
  text-decoration: none;
  background-color: white;
  color: #5e0734;
  display: block;
  -webkit-animation-duration: 1.5s;
  -webkit-animation-timing-function: ease-out;
  -webkit-animation-fill-mode: forwards;
  animation-duration: 1.5s;
  animation-fill-mode: forwards;
  transition: color, background-color, width 0.2s linear;/*WIDTH IGNORED*/
  border: 2px solid #5e0734;
  overflow: hidden;
  white-space: nowrap;
  margin-right: 0;
  margin-left: 5px;
  margin-top: 0;
  margin-bottom: 5px;
  padding: 0;
}

.home-bar:hover {
  background-color: #5e0734;
  color: white;
  width: 100%;/*WIDTH IGNORED*/
  text-decoration: none;
}

#bar0 {
  -webkit-animation-name: grow0;
  animation-name: grow0;
}

@keyframes grow0 {
  from {
    width: 0%;
  }
  to {
    width: 75%;
  }
}
<a href="#" id="bar0" class="home-bar">LINK</a>

注意 - 我已经测试过在鼠标悬停时更改链接高度的效果,它是有效的。只有宽度不起作用。也许这与页面加载时的动画有关。

所以你想在鼠标悬停链接时更改/动画宽度,而不是在页面加载时?我不确定我是否理解正确? - webta.st.ic
@MrBuggy 抱歉,我会讲得更清楚。有五个链接,每个链接在页面加载时会展开一些div的百分比(小于100%)。这个效果非常好。然后,我希望在鼠标悬停时出现额外的过渡效果,将链接的宽度进一步扩展到100%。 - Alex
为了让它更清晰,请将您的整个代码放入片段中,并描述发生了什么以及应该发生什么... - webta.st.ic
1
@MrLister 是的,那一定是发生了什么,但我不知道为什么。也许是因为 animation-fill-mode: forwards; 的缘故? - Alex
@MrBuggy 基本上是,但是黑边会不断增长,而不是固定在末尾。 - Alex
显示剩余2条评论
1个回答

3
当您使用动画设置宽度时,您将覆盖任何其他已定义的CSS宽度,包括悬停定义的宽度。关键帧内的样式比任何其他样式更具体:
CSS动画会影响计算属性值。通过在CSS级别(用于CSS动画)添加指定的值来实现此效果,该值将产生当前动画状态的正确计算值。如 [CSS3CASCADE]所定义,“动画覆盖所有常规规则”,但被!important规则覆盖。ref 解决方法是考虑宽度/最大宽度属性,以避免混淆。

.home-bar {
  text-decoration: none;
  background-color: white;
  color: #5e0734;
  display: block;
  animation: grow0 1.5s forwards;
  transition: color, background-color, max-width 0.2s linear;
  border: 2px solid #5e0734;
  max-width: 75%; /*Set max-wdith*/
}

.home-bar:hover {
  background-color: #5e0734;
  color: white;
  max-width: 100%; /* Update the max-width of hover*/
  text-decoration: none;
}

/*Animate width to 100%*/
@keyframes grow0 {
  from {
    width: 10%;
  }
  to {
    width: 100%;
  }
}
<a href="#" id="bar0" class="home-bar">LINK</a>


这似乎是原因。我尝试将! important添加到过渡内容中,但没有帮助。 - Alex
@Alex 然后覆盖动画本身。 - Mr Lister
@TemaniAfif 抱歉,我在评论中途发送了。Fiddle已更新。 - Alex
@TemaniAfif,谢谢你的回答。你能解释一下 not(#randomid_58) 是什么意思吗? - Alex
通过添加一个ID,@Alex可以使指定更高,但由于我不能将相同的ID添加到所有内容中,所以我使用not()来选择所有没有这个ID的内容,而且由于没有人有这个ID,它会选择全部;) 更多信息请参见:https://stackoverflow.com/a/49742059/8620333 - Temani Afif
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接