CSS3开销边框顶部过渡看起来像边框底部

时间:2016-03-04 07:57:25

标签: css css3

尝试获取CSS3过渡以在我的链接上方生成border-top行。出于某种原因,它只是像border-bottom一样不断增长。以下是使用SASS混音的代码。它目前正在发挥作用,但从底部而不是顶部发展。

#linkReport {
    padding-left: 20px;
    border-top: 0px solid transparent;
    display: inline-block;
    text-decoration: none;
    color: $defaultText;
    padding: 3px;

    &:after {
        @include outsideLinks;
    }

    &:hover:after {
      @include outsideHover;
    }
}

 @mixin outsideLinks() {
    border-top: 2px solid grey;
    content: '';
    display: block;
    width: 0;
    -webkit-transition: 0.5s ease;
    transition: 0.5s ease;
}

@mixin outsideHover() {
    width: 100%;
}

下面是使用上面代码生成的编译CSS创建的演示。



#linkReport {
  padding-left: 20px;
  border-top: 0px solid transparent;
  display: inline-block;
  text-decoration: none;
  color: black;
  padding: 3px;
}
#linkReport:after {
  border-top: 2px solid grey;
  content: '';
  display: block;
  width: 0;
  -webkit-transition: 0.5s ease;
  transition: 0.5s ease;
}
#linkReport:hover:after {
  width: 100%;
}

<a id='linkReport' href='#'>Some Text</a>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

为什么顶部边框出现在底部?

伪元素设置为display: block,因此默认情况下它将显示在主元素内容下面的下一行中。这就是为什么伪元素的border-top看起来好像是border-bottom的原因。

演示问题:(添加了高度和背景颜色,以便您可以看到我的意思)

#linkReport {
  padding-left: 20px;
  border-top: 0px solid transparent;
  display: inline-block;
  text-decoration: none;
  color: black;
  padding: 3px;
}
#linkReport:after {
  border-top: 2px solid grey;
  content: '';
  display: block;
  width: 0;
  height: 10px;
  background: cyan;
  -webkit-transition: 0.5s ease;
  transition: 0.5s ease;
}
#linkReport:hover:after {
  width: 100%;
}
<a id="linkReport">Some text</a>

解决方案是什么?

不是设置display: block,而是将伪元素绝对地放在父元素上,如下面的代码片段所示。

#linkReport {
  position: relative; /* add this */
  padding-left: 20px;
  border-top: 0px solid transparent;
  display: inline-block;
  text-decoration: none;
  color: black;
  padding: 3px;
}
#linkReport:after {
  border-top: 2px solid grey;
  content: '';
  /* display: block; remove this */
  position: absolute; /* add this */
  top: 0px; /* add this */
  left: 0px; /* add this */
  width: 0;
  -webkit-transition: 0.5s ease;
  transition: 0.5s ease;
}
#linkReport:hover:after {
  width: 100%;
}
<a id="linkReport">Some text</a>

相关问题