【问题标题】:How do I animate ::after elements width from right to left?如何为 ::after 元素宽度从右到左设置动画?
【发布时间】:2017-09-25 14:04:08
【问题描述】:

我有一个按钮,它使用 ::after 伪来填充背景。目前它从左到右填充,这在宽度从 0 到 100% 时是有意义的。但是,我希望它翻转它的填充方式。

a.project--link {
  margin: 2rem auto 0 auto;
  padding: 1rem 0;
  display: block;
  border: 1px solid black;
  box-shadow: 0 0 10px rgba(red, .2);
  width: 100%;
  transition: all .2s ease;
  z-index: 1;
  }
  a.project--link:hover {
    box-shadow: 0 0 10px rgba(red, .7);
    transform: scale(1.02);
    transition: all .2s ease;
  }
  a.project--link::after {
    display: block;
    content: '';
    height: 100%;
    width: 0;
    top: 0;
    z-index: -1;
    background-color: red;
    position: absolute;
  }

a.project--link:hover::after {
  width: 100%;
  transition: .3s linear;
}
<a href="#" class="project--link">View Project</a>

如果有人能阐明如何翻转动画,那将是一个巨大的帮助。

【问题讨论】:

  • 您能否发布 CSS 以及您的标记,所以我们有一个有效的演示?
  • 好的,我会尽快将它添加到codepen
  • Patrick,理想情况下,您应该将代码放在帖子本身,而不是第三方网站。

标签: html css animation flip


【解决方案1】:

使用transform: scaleX() 代替width 并使用transform-origin 来控制方向。

a.project--link {
  margin: 2rem auto 0 auto;
  padding: 1rem 0;
  display: block;
  border: 1px solid black;
  box-shadow: 0 0 10px rgba(red, .2);
  width: 100%;
  transition: all .2s ease;
  z-index: 1;
  position: relative;
}

a.project--link:hover {
  box-shadow: 0 0 10px rgba(red, .7);
  transform: scale(1.02);
  transition: all .2s ease;
  transform-origin: 0 100%;
}

a.project--link::after {
  display: block;
  content: '';
  height: 100%;
  top: 0;
  width: 100%;
  z-index: -1;
  background-color: red;
  position: absolute;
  transition: .3s linear;
  transform: scaleX(0);
  transform-origin: 100% 0;
}

a.project--link:hover::after {
  transform: scaleX(1);
}
<a href="#" class="project--link">View Project</a>

【讨论】:

  • @PatrickWhitehouse 啊感谢您的标记。更新了我的答案
  • 干杯!您能否解释一下为什么它不适用于宽度?
  • @PatrickWhitehouse 因为 transform-origin 适用于 transform 属性...
  • 啊!非常感谢。
猜你喜欢
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多