CSS转换忽略宽度

Ale*_*lex 7 css css3 css-transitions css-animations

我有一个标签,显示为一个块.在页面加载时,其宽度通过css 动画从0增加到包含div的某个百分比(小提琴包含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%;
  }
}
Run Code Online (Sandbox Code Playgroud)
<a href="#" id="bar0" class="home-bar">LINK</a>
Run Code Online (Sandbox Code Playgroud)

注意 - 我已经通过在悬停时更改链接的高度来测试它,并且它有效.只有宽度不起作用.也许它与页面加载时的动画有关.

Tem*_*fif 3

当您使用动画设置宽度时,您将覆盖使用 CSS 定义的任何其他宽度,包括由悬停定义的宽度。关键帧内的样式比任何其他样式都更具体:

CSS 动画影响计算的属性值。通过向 CSS 级联 ([CSS3CASCADE])(在 CSS 动画级别)添加指定值来实现此效果,该值将为动画的当前状态生成正确的计算值。正如[CSS3CASCADE]中所定义的, 动画会覆盖所有普通规则,但会被 !important 规则覆盖。参考

解决方法是同时考虑 width/max-width 属性以避免这种混淆:

.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%;
  }
}
Run Code Online (Sandbox Code Playgroud)
<a href="#" id="bar0" class="home-bar">LINK</a>
Run Code Online (Sandbox Code Playgroud)