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

CSS斜切按钮hover背景色与:before过渡不同步问题求解

问题修复:按钮hover时背景与伪元素过渡同步问题

问题

按钮hover时,主体背景色和:before伪元素的右侧边框色过渡不同步,呈现瞬间切换的割裂效果。

原代码

CSS

.btn-primary {
  background-color: #2c9ff5;
  border-color: #2c9ff5;
  text-transform: capitalize;
}

.btn.btn-primary:hover {
  background-color: #45aff6;
  border-color: #45aff6;
}

.btn-donate {
  background-color: #053a86;
  color: #fff;
  margin-left: 15px;
  padding-left: 40px;
  padding-right: 30px;
  padding-top: 2px;
  text-transform: uppercase;
  border-radius: 4px 0 0 4px;
  height: 30px;
  position: relative;
  border: none;
}

.btn-donate:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border-top: 30px solid white;
  border-right: 20px solid #053a86;
  width: 0;
}

.btn-donate:hover::before {
  border-right: 20px solid #45aff6;
}

HTML

<a href="#" class="btn btn-primary btn-donate">Donate</a>

修复方案

问题核心是没有给按钮和伪元素添加过渡动画属性,导致颜色变化无平滑过渡,自然无法同步。只需添加过渡规则即可解决:

修改后的完整代码

CSS

.btn-primary {
  background-color: #2c9ff5;
  border-color: #2c9ff5;
  text-transform: capitalize;
}

.btn.btn-primary:hover {
  background-color: #45aff6;
  border-color: #45aff6;
}

.btn-donate {
  background-color: #053a86;
  color: #fff;
  margin-left: 15px;
  padding-left: 40px;
  padding-right: 30px;
  padding-top: 2px;
  text-transform: uppercase;
  border-radius: 4px 0 0 4px;
  height: 30px;
  position: relative;
  border: none;
  /* 给按钮背景色添加过渡动画 */
  transition: background-color 0.3s ease;
}

.btn-donate:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border-top: 30px solid white;
  border-right: 20px solid #053a86;
  width: 0;
  /* 给伪元素右侧边框色添加过渡,与按钮过渡参数完全一致 */
  transition: border-right-color 0.3s ease;
}

/* 明确按钮hover背景色,避免优先级冲突 */
.btn-donate:hover {
  background-color: #45aff6;
}

.btn-donate:hover::before {
  border-right: 20px solid #45aff6;
}

HTML

<a href="#" class="btn btn-primary btn-donate">Donate</a>

关键说明

  • 过渡参数0.3s ease是通用平滑曲线,可根据需求调整时长(如0.2s更快、0.5s更慢)
  • 必须保证按钮和伪元素的过渡参数完全一致,才能让两者颜色变化节奏同步
  • 单独声明.btn-donate:hover的背景色,是为了避免继承.btn-primary:hover时可能出现的优先级问题,确保颜色切换准确

内容的提问来源于stack exchange,提问作者Elaine Byene

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:45:49