看起来像 border-bottom 的 CSS3 Overhead border-top transition

标签 css

尝试通过 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>

最佳答案

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

伪元素设置为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>

关于看起来像 border-bottom 的 CSS3 Overhead border-top transition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790816/

相关文章:

html - 使类不可见

html - 100% 宽度的元素渲染 <td> 不同

javascript - 在新窗口中打开选项卡,然后

html - 需要使用:fixed but still need element in flow.位置怎么办?

html - IE 8 访问过的链接右移

javascript - 在循环中显示 HTML 元素

HTML/CSS - 打印时避免单元格 split

html - 悬停一个 div 时更改两个元素

javascript - 如何自定义 Rails 应用程序模板

jquery - 是否可以在不刷新页面的情况下更改元素上的光标?