You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS按钮::before伪元素内容溢出,如何将其限制在按钮内部

解决方法

要把::before伪元素限制在按钮内部,只需要给button元素添加overflow: hidden属性即可。该属性会裁剪所有超出元素盒模型边界的内容,绝对定位的伪元素也会被限制在按钮范围内,不会向外溢出。

另外你现有代码还存在几个需要同步修正的问题,否则按钮交互效果会异常:

  • button::before规则中的z-index: ;是无效写法,修改为z-index: -1;,避免伪元素覆盖按钮文字
  • 按钮的文字层级需要高于伪元素,确保hover时文字可见
  • 常规布局场景下可以将position: absolute;改为position: relative;,适配页面流排版

以下是修正后的完整代码:

button {
  padding: 0.9em 2em;
  border: 2px solid #17C3B2;
  position: relative; /* 有绝对定位需求可以改回absolute */
  overflow: hidden; /* 新增属性,限制内部内容不溢出 */
  background-color: transparent;
  text-align: center;
  text-transform: uppercase;
  font-size: 16px;
  color: #17C3B2;
  transition: .3s;
  display: block;
  font-family: inherit;
  z-index: 1;
}

button::before {
  content: '';
  width: 0;
  height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  background: #17C3B2;
  transition: .5s ease;
  display: block;
  z-index: -1; /* 修复无效的z-index写法 */
}

button span {
  position: absolute;
  left: 0;
  top: 0;
  width: 10%;
  height: 10%;
  background: transparent;
  z-index: 1;
}

button span::before {
  content: "";
  display: block;
  position: absolute;
  width: 8%;
  height: 500%;
  background: var(--lightgray, #eee); /* 增加默认值避免CSS变量未定义报错 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-60deg);
  transition: all 0.3s;
}

button:hover::before {
  transform: translate(-50%, -50%) rotate(44deg);
  width: 100%;
}

button:hover {
  color: #111;
}
<button>hover me
  <span></span>
</button>

内容的提问来源于stack exchange,提问作者Tech Tips

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:54:00