如何使用CSS制作边框过渡扩展动画?

5
我想创建一个CSS过渡效果,在:hover时,a href元素的border-bottom扩展到链接的宽度。
我找到的是一个CSS解决方案,其中background width被动画化:http://jsfiddle.net/mfn5nefb/82/ 但这不是我想要的,因为在导航标签上单击后,我希望保留边框。所以我必须直接动画化边框,而不是背景。
<!-- assume the border-bottom is only applied to an active=clicked navigation tab -->
<h1 style="border-bottom: 3px solid green;">CSS IS AWESOME</h1>

h1 {
    color: #666;
    position: relative;
    display: inline-block;
}

h1:after {
    position: absolute;
    left: 50%;
    content: '';
    height: 40px;
    height: 5px;
    background: #f00;
    transition: all 0.5s linear;
    width: 0;
    bottom: 0;  
}

h1:hover:after {
    width: 270px;
    margin-left: -135px;
}

在这里,您可以看到“活动”链接会出现绿色边框。当鼠标悬停时,我希望其他选项卡也能进行动画效果,但仅限于边框本身。目前,背景是被动画的,它出现在边框之上,因此看起来不对齐。


1
关于在悬停时从中心扩展底部边框的相关内容。 - web-tiki
1个回答

15

你仍然可以通过使用伪元素(带有background)并在hover时扩展它来实现此目的。所需的全部就是将 bottom 属性的值设置为预期 border-width 的倒数,并且还要将伪元素的height设置为与border-width相同。

h1 {
  color: #666;
  position: relative;
  display: inline-block;
}
h1:after {
  position: absolute;
  left: 50%;
  content: '';
  height: 3px;
  background: #f00;
  transition: all 0.5s linear;
  width: 0;
  bottom: -3px;
}
h1:hover:after {
  width: 100%;
  left: 0px;
}
<!-- assume the border-bottom is only applied to an active=clicked navigation tab -->
<h1 style="border-bottom: 3px solid green;">Tab1</h1>
<h1>Tab2</h1>


使用border属性本身实现相同效果的另一种方法是在下面的代码段中使用transform: scale。 这里的scaleX(0)使元素的原始宽度为0,在hover时使用scaleX(1)转换为全宽。 由于默认的transform-origin在X轴上的50%,因此边框看起来就像从中心扩展。


h1 {
  color: #666;
  position: relative;
  display: inline-block;
}
h1:after {
  position: absolute;
  left: 0%;
  top: 0%;
  content: '';
  height: 100%;
  transition: all 0.5s linear;
  width: 100%;
  border-bottom: 3px solid red;
  transform: scaleX(0);
}
h1:hover:after {
  transform: scale(1);
}
<!-- assume the border-bottom is only applied to an active=clicked navigation tab -->
<h1 style="border-bottom: 3px solid green;">Tab1</h1>
<h1>Tab2</h1>


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