【问题标题】:Why is there extra space around pseudo elements?为什么伪元素周围有额外的空间?
【发布时间】:2026-01-21 11:10:01
【问题描述】:

我正在使用伪元素 ::after 和 ::before 在我的按钮上制作动画。我已经在 3 个不同的平台上重现了这个问题。很难看到,但角落有额外的空间。放大使它更容易看到。

我正在使用 Bootstrap,但我在使用和不使用 Bootstrap 的情况下都复制了它。

http://codepen.io/sinrise/pen/vLaGzN

<a href="#" class="btn btn-default btn-action">Test Button</button>

正常

悬停

【问题讨论】:

  • 你的意思是为什么它不覆盖边界? ...请制作一张放大的图像,以准确显示您的意思。

标签: css twitter-bootstrap css-animations pseudo-element


【解决方案1】:

更新

进行了更多测试和研究,发现了真正的问题...从 a.btn-action 规则中删除 z-index: 1;

a.btn-action {
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
    color: black;
    transition: color 0.4s;
    transition-delay: 0.3s;
}

Updated codepen

【讨论】:

  • 谢谢,但这完全破坏了动画。
  • @sinrise 更新了我的答案
  • 酷。这似乎确实解决了 Codepen 中的问题,但不幸的是 z-index 属性在我的实际项目中是必需的。我尝试从锚点中删除 z-index 并将其放在它的父级上。这删除了右侧的额外空间,但左侧有额外的空间! (这只是笔中的角落。)我已经搞砸了在悬停时为 btn div 添加背景并延迟它,但它是如此 hacky。这一定只是另一个 CSS 错误?
【解决方案2】:

删除悬停伪类的 transform3d 过渡,并为 ::before 和 ::after 伪选择器添加height: 100%;,以定位您要使用的悬停动画。

a.btn-action {
    position: relative;
    box-sizing: border-box;
    color: black;
    transition: color 0.4s;
    transition-delay: 0.3s;
}
a.btn-action::before, a.btn-action::after {
    position: absolute;
    top: 0;
    left: 0;
    content: "";
    width: 100%;
    height: 0;
    background: rgba(0, 0, 0, 0.1);
    -webkit-transition: all 0.2s ease 0s;
    -moz-transition: all 0.2s ease 0s;
    -ms-transition: all 0.2s ease 0s;
    -o-transition: all 0.2s ease 0s;
   transition: all 0.2s ease 0s;
   z-index: -1;
   box-sizing: border-box;
}

a.btn-action:hover::before, 
a.btn-action:hover::after {
    height:100%;
}

修改后的演示:Codepen

【讨论】:

  • 现已测试并修复。溢出隐藏导致了这个问题。立即更新代码
  • 谢谢!这是美丽和完美的!它工作得很好。非常感谢!
  • 如果你再次检查我用 z-index:1 Codepen创建的 codepen
最近更新 更多