如何使用CSS扩展边界过渡动画?

时间:2016-01-28 16:19:46

标签: html css css3 border

我正在尝试创建一个CSS转换,其中border-bottom a href元素在:hover上扩展到链接的宽度。

我能找到的是background width动画的CSS解决方案: 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 个答案:

答案 0 :(得分:13)

您仍然可以通过使用伪元素(background)并在hover上展开它来实现此目的。所需要的只是将bottom属性的值设置为预期border-width的倒数,并将伪元素的height设置为与{{1}相同}}

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将元素的原始宽度设为0,scaleX(0)使用hover将其转换为全宽。由于默认scaleX(1)位于X轴的transform-origin,因此边框看起来好像从中心扩展。

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);
}